| Author |
Possible Loss of Precision
|
Rob Sweeny
Greenhorn
Joined: Jan 14, 2010
Posts: 16
|
|
Hi All,
I've Included two source files that I would think would do the same thing, but they dont
Using Compound Assignment Operators I have no compilation errors.
But when I convert the code to strict Assignment Operators I get "Possible Loss of Precision"
1. How do I change the 2nd source code so it doesn't give me these errors
2. Why is there a difference. Why doesn't the Compound Assignment Operators give me the same errors.
No Compilation Errors:
Compliation Errors:
Compilation Error:
src\com\scjaexam\tutorial\pirates\AssignmentOperators.java:11: possible loss of
precision
found : int
required: byte
_________System.out.println(a = a + 3); // 13
_____________________________^
Thanks!
|
 |
W. Joe Smith
Ranch Hand
Joined: Feb 10, 2009
Posts: 710
|
|
When you are doing this:
The addition operation is returning an int. You are trying to assign an int to a byte, which is giving you a warning. You can either switch a's declaration to be an int, or explicity cast all of your additions to byte, essentially telling the compiler you are aware there is a possible loss of precision but you want to do it anyway.
|
SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
|
 |
Rob Sweeny
Greenhorn
Joined: Jan 14, 2010
Posts: 16
|
|
How do i "explicity cast all of your additions to byte" ?
Doesn't work.
|
 |
W. Joe Smith
Ranch Hand
Joined: Feb 10, 2009
Posts: 710
|
|
You explicitly cast the additions like this:
This is telling the compiler that you are taking the result of your addition, no matter what it is, and changing it to a byte. If any of your additions should go beyond the bounds of a byte, though, you will get unexpected results.
I would suggest doing a Google search for explicit casting in java, as it has many other uses.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
W. Joe Smith wrote: . . . I would suggest [a] search for explicit casting in java . . .
You will also find something about it in the Java™ Language Specification, but it is by no means easy reading.
|
 |
 |
|
|
subject: Possible Loss of Precision
|
|
|