Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

no compile due to loss of precision

 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have these lines in my code.

public class MyClass{
byte completion;

public MyClass(){
completion = 0;
}

public void write(int nextBits, int bitNum){
byte btw = 8 - completion;
}
}

Of course there is much more, but this is the important part.
I keep getting the error message seido ga ochiteiru kanosei, which in English means something like "There is a possibility of loss of precision" and another message which tells me that the program is expecting a byte but getting an int. So it won't compile.
I get this message for several lines, but this is the first line.
I don't see where the int is. btw and completion are both bytes. I thought that the program is treating 8 as an int, so I tried this line

byte eight = (byte) 8;

and then changed the other line to

byte btw = eight - completion;

but I got the same error message.
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to cast the result of the subtraction:
 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. But I wonder why you have to cast the result to a byte. Does the subtraction operation automatically turn every byte into an int?
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But I wonder why you have to cast the result to a byte. Does the subtraction operation automatically turn every byte into an int?


No the subtraction operator won't do that.
This is because when you cast from a higher type (in this case an int) to lower(byte) the compiler expects that you know that you know what you are doing and hence it requires an explicit cast.


Hope this helps
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The result of every arithmetic operation in Java will be at least int, never short, char or byte.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic