jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Possible 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 "Possible Loss of Precision" Watch "Possible Loss of Precision" New topic

Possible Loss of Precision

Rob Sweeny

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
found : int
required: byte
_________System.out.println(a = a + 3); // 13

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.

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

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

Joined: Oct 13, 2005
Posts: 44013
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.
Have you checked out Aspose?
subject: Possible Loss of Precision
It's not a secret anymore!