3 Replies Latest reply: Apr 7, 2008 6:19 AM by 800308 RSS

    byte data type-arithmetic

    807601
      what is the internal mechanism of adding two byte type of data type?
      why the summation value is being converted to int type?
        • 1. Re: byte data type-arithmetic
          JosAH
          mahisingh wrote:
          what is the internal mechanism of adding two byte type of data type?
          why the summation value is being converted to int type?
          That's the way it is defined in Java: bytes are (sign) extended to ints and the results are added and is of type int as well.

          kind regards,

          Jos
          • 2. Re: byte data type-arithmetic
            791266
            JosAH wrote:
            mahisingh wrote:
            what is the internal mechanism of adding two byte type of data type?
            why the summation value is being converted to int type?
            That's the way it is defined in Java: bytes are (sign) extended to ints and the results are added and is of type int as well.

            kind regards,

            Jos
            @Op. You can read more about it in section 4.2.2 in the JLS:
            http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html

            "If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (?5.1.5) to type long by numeric promotion (?5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion."

            Kaj
            • 3. Re: byte data type-arithmetic
              800308
              mahi,

              Java doesn't do byte or char arithmetic, instead it "promotes" all "lesser types" to integer's and just does integer arithmetic... if you add two char's the result is an integer.

              for instance
              package forums;
              class CharAddTesterator
              {
                public static void main(String[] args) {
                  char a = 'a';
                  char x = 1;
                  char b = a+x;
                  System.out.println(b);
                }
              }
              produces:
              C:\Java\home\src\forums\CharAddTesterator.java:7: possible loss of precision
              found   : int
              required: char
                  char b = a+x;
                            ^
              1 error
              to fix this:
                  char b = (char)(a+x);
              Don't argue with it (trust me you won't win)... just accept it and move on.

              Keith.