4 Replies Latest reply on Apr 4, 2002 3:18 PM by 807554

    Possible loss of precision and santiy

    807554
      I'm having a bit of a problem dealing with bitwise operators and the compiler complaining of
      possible losses of precision (although I know there won't be). So I constructed some "do or die" code ;

      public class byteWise {
           public static void main(String[] args) {
                byte a=1;
                byte b=64;
                byte c= a & b;
           }
      }

      and javac produced this reply:

      D:\Java\byteWise.java:5: possible loss of precision
      found : int
      required: byte
                byte c= a & b;
      ^
      1 error

      What does it mean, "found int, expected byte" ? There's no int in the entire source code.

      Please help!
        • 1. Re: Possible loss of precision and santiy
          807554
          when you have two bytes on the right side of the assignment operator, they are first promoted to int values before being added. So, to assign them to a byte, you have to explicitly cast them as a byte value. like this.
          byte a = 1;
          byte b = 2;
          byte c = (byte)(a + b);
          • 2. Re: Possible loss of precision and santiy
            807554
            Possible loss of precision only denotes that a specific mathematical operation you are performing provides a value that of a data type different than that you are storing it into. It is simply type checking that is performed by the compiler. If you want to bypass this, then you need to do an explitic cast of the data type to the type that you are assigning the value.

            Example:

            double bob = 5.5;
            int jack = 3;

            int sue = bob + jack; //Possible loss of precision.
            int sue = (int)(bob + jack) //This tells the compiler I know what I am doing.
            • 3. Re: Possible loss of precision and santiy
              807554
              Possible loss of precision only denotes that a specific mathematical operation you are performing provides a value that of a data type different than that you are storing it into. It is simply type checking that is performed by the compiler. If you want to bypass this, then you need to do an explitic cast of the data type to the type that you are assigning the value.

              Example:

              double bob = 5.5;
              int jack = 3;

              int sue = bob + jack; //Possible loss of precision.
              int sue = (int)(bob + jack) //This tells the compiler I know what I am doing.

              -Jason Thomas
              • 4. Re: Possible loss of precision and santiy
                807554
                Sorted, thanks muchly!