Ok. I think this is impossible. If you think the same, you do not need to post an answer. I have read a few lines of Chapter 5. Conversions and Promotions and it seems chapter 5 has no mention of disabling Conversions and Promotions in Java.
Here is my motivation:
long uADD(long a, long b) {
try {
long c;
c = 0;
boolean carry; //carry flag; true: need to carry; false: no need to carry
carry = false;
for (int i = 0; i < 64; ++i) { //i loops from 0 to 63,
if (((((a >>> i) & 1) ^ ((b >>> i)) & 1) != 0) ^ carry) { //calculate the ith digit of the sum
c += (1 << i);
}
if (((((a >>> i) & 1) & ((b >>> i) & 1)) != 0) || (carry && ((((a >>> i) & 1) ^ ((b >>> i) & 1)) != 0))) {
carry = true; //calculate the carry flag which will be used for calculation of the (i+1)th digit
} else {
carry = false;
}
}
if (carry) { //check if there is a last carry flag
throw new ArithmeticException(); //throw arithmetic exception if true
}
return c;
} catch (ArithmeticException arithmExcep) {
throw new ArithmeticException("Unsigned Long integer Overflow during Addition");
}
}
So basically, I am writing a method that will do unsigned addition for long integer. It will throw arithmetic exception if overflow. The code above is not readable enough, so I should try to explain it.
First, there is a for
loop where i
loops from 0
to 63
.
Then, the first if
statement acts as the sum output of the full adder, it uses the i
th digit of a
and that of b
and carry
flag to calculate the i + 1
th digit (true
or false
). (Note that i = 0
corresponds to the units digit.) If true
, it adds 1 << i
to c
, where c
is initially 0
.
After that, the second if
statement acts as the carry flag output of the full adder, it uses again the i
th digit of a
and that of b
and carry
flag to calculate the carry
flag of the i + 1
th digit. If true
, set the new carry
flag to true
, if false
, set the new carry
flag false
.
Finally, after exit the for
loop, check if the carry
flag is true
. If true
, throw arithmetic exception.
However, the above code does not work. After debugging, it turns out the problem occurs at
c += (1 << i);
The correct code should be:
c += (1L << i);
because Java will automatically promote integer 1 << i
to Long and add it to c
, showing no warning to me.
I have several questions regarding to this.
- Is it possible to disable automatic promotion of one data type to another
- How often does automatic promotion causing problem to you?
- Is it possible to tweak the IDE so that it shows a warning to me when automatic promotion occurs? (I am using NetBeans IDE 7.3.1 at the moment.)
Sorry for lots of questions and the hard to read code. I will be studying CS in September so I try to write some code in Java to familiarize myself with Java.