File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes no compile due to loss of precision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "no compile due to loss of precision" Watch "no compile due to loss of precision" New topic
Author

no compile due to loss of precision

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
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

Joined: Dec 17, 2003
Posts: 624

You need to cast the result of the subtraction:
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
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

Joined: Jun 06, 2007
Posts: 2718
    
    6

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


SCJP, SCWCD.
|Asking Good Questions|
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

The result of every arithmetic operation in Java will be at least int, never short, char or byte.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: no compile due to loss of precision