Reputation: 956
Simple code no problem
long x = Integer.MAX_VALUE;
System.out.println(x * 2 + "...." + Long.MAX_VALUE);
= 4294967294....9223372036854775807
but what is happening here? why -2
System.out.println(2 * Integer.MAX_VALUE + "...." + Long.MAX_VALUE);
= -2....9223372036854775807
and why elements is 149998, doesn't the compiler converts these to long?
long elements = 2 * Integer.MAX_VALUE + 150000;
System.out.println(elements + "...." + Long.MAX_VALUE);
149998....9223372036854775807
-thanks
Upvotes: 0
Views: 223
Reputation: 513
I don't have enough rep to comment yet :(.
The Oracle Java Tutorials confirmed that it will convert the data to the primitive type long. Since you're adding an int and a long, the compiler will add the data before it converts it to a long. If you really want it to be a long the entire time, you'd have to type cast.
EX;
// (long) is typcasted
long elements = 2 * (long) Integer.MAX_VALUE + 150000;
//prints elements as a long t + "" + max value
System.out.println(elements + "...." + Long.MAX_VALUE);
Type is casting preformed by adding the wanted primitive type in front of the current data type.
Upvotes: 0
Reputation: 6213
and why elements is 149998, doesn't the compiler converts these to long?
It does, but only after the arithmetic. So you've got int*int + int, which is an int. It will then cast it to a long. However, at this point you've got an integer overflow (i.e. it went beyond the bounds of an integer)
you need to convert the numbers of the right to a long first
long elements = 2L * Integer.MAX_VALUE + 150000;
or
long elements = 2 * (long)Integer.MAX_VALUE + 150000;
B
Upvotes: 3
Reputation: 35587
Integer.MAX_VALUE =2147483647=01111111 11111111 11111111 11111111
And
2*Integer.MAX_VALUE=4294967294=2*(01111111 11111111 11111111 11111111)
=this will result a 33-bit value
But in Java int
can represent maximum of 32bit.
Upvotes: 1
Reputation: 63708
Promote variables from integer to long.
long elements = 2 * Integer.MAX_VALUE + 150000;
should be
long elements = 2L * Integer.MAX_VALUE + 150000;
The evaluation of original statement,
long elements = 2 * Integer.MAX_VALUE + 150000;
is equivalent to
long elements = (long)(2 * Integer.MAX_VALUE + 150000);
Upvotes: 6