Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Compiler error ! Not sure why

P Teng
Greenhorn
Posts: 16
• 1
Hi

why does line 1 not give the same error as line 2 (possible loss of precision). Why is the 2 in line 1 not treated as an integer.

Sreedhar Sivan
Greenhorn
Posts: 1
When you apply mathematical operations on byte, they will always result in int. To protect from overflow it will not allow you to store an int into a byte.

That is the reason you are getting the error as "possible loss pf precision".

Change the code like this and it will work,

Class ByteTest {

public static void main(String[] args) {

int b = 100;

Only change is byte to int.

Good that you posted in Javaranch. All the best...

Sreedhar S
Java developer

P Teng
Greenhorn
Posts: 16
Hello,

but why does this not apply to b *= 1 as that too is a mathematical action.

Matthew Brown
Bartender
Posts: 4568
9
The operator *= (and similarly +=, -= etc) have an implicit cast built in, which is why it works. So:
is equivalent to

P Teng
Greenhorn
Posts: 16
Excellent
That explains it.
Perhaps thats why it does not like b = b * 2 but likes the former b *= 2

Thanks Matthew.

Mala Gupta
Author
Ranch Hand
Posts: 359
10
P Teng,

Apart from the shortcut assignment operators (example +=, -=, *=) and unary operators (+, -, ++, --), the following rules are applied to a binary expression:

1) If either operand is of type double, the other is converted to double.
2) Otherwise, if either operand is of type float, the other is converted to float.
3) Otherwise, if either operand is of type long, the other is converted to long.
4) Otherwise, both operands are converted to type int.

As visible from the above list, the operands of type char, byte and short are atleast promoted to an int, when an expression is evaluated.

In the following example, the type of the resultant expression is double, because one of the operands is of type double.

cheers
Mala

Vijitha Kumara
Bartender
Posts: 3918
10
Welcome to CodeRanch, Sreedhar Sivan

And, please UseCodeTags while posting code which makes it much easier to read.

P Teng
Greenhorn
Posts: 16
Thank you all.