Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

Operations on "byte" Data Type Values

This section provides a tutorial example on how 'byte' values are casted to 'int' values when they are invovled in arithmetic, comparison and bitwise operations.

Actually, there is no operations defined in Java that works directly on "byte" data type values.

But "byte" data type values can participate all operations defined for integer values. More precisely:

  • When a "byte" value is involved in an arithmetic operation like +, -, *, /, or %, it will be casted to an "int" value before entering the operation.
  • When a "byte" value is involved in a comparison operation like ==, !=, >, <, >=, or <=, it will be casted to an "int" value before entering the operation.
  • When a "byte" value is involved in a bitwise operation like &, |, ^, or ~, it will be casted to an "int" value before entering the operation.
  • When a "byte" value is involved in a shift operation like <<, >>, or >>>, it will be casted to an "int" value before entering the operation.

To validate those rules mentioned above, I wrote the following sample program, ByteOperations.java:

/**
 * ByteOperations.java
 * Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
 */
public class ByteOperations {
   public static void main(String[] arg) {
      byte b1 = 127;
      int o1 = (b1+b1-0)*5/10; // arithmetic operations

      byte b2 = 0x0000007F;
      boolean o2 = b2 > b2 || b2 != b2 || b2 == b2; // comparisons

      byte b3 = (byte) 127; 
      int o3 = b3 & 0x0000000F | 0x00000070; // bitwise operations

      byte b4 = (byte) 0x0000007F;
      int o4 = b4 >> 4 << 4; // shift operations

      System.out.println("o1: "+o1);
      System.out.println("o2: "+o2);
      System.out.println("o3: "+o3);
      System.out.println("o4: "+o4);
   }
}

After executing this program, I got this output with no surprises:

o1: 127
o2: true
o3: 127
o4: 112

Sections in This Chapter

What Are Bits and Bytes

"byte" Data Type and Implicit Casting

Operations on "byte" Data Type Values

Bitwise Operations on "byte" Values

Bitwise Operations on "byte" Values - Example Program

Shift Operations - Left, Right or Unsigned Right Shift

Dr. Herong Yang, updated in 2008
Operations on "byte" Data Type Values