• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compiler error ! Not sure why

 
P Teng
Greenhorn
Posts: 16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Thank you very much for your reply.
but why does this not apply to b *= 1 as that too is a mathematical action.

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 296
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch, Sreedhar Sivan

And, please UseCodeTags while posting code which makes it much easier to read.
 
P Teng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic