The byte Data Type - Java Language Basics

Java examples for Language Basics:byte

Introduction

The byte data type is an 8-bit signed Java primitive integer data type.

Its range is -128 to 127 (-2^7 to 2^7 - 1).

This is the smallest integer data type available in Java.

There are no byte literals.

You can assign any int literal that falls in the range of byte to a byte variable.

For example,

byte b1 = 12; 
byte b2 = -11; 

Assigning an int literal to a byte variable and the value is outside the range of the byte data type generates a compiler error.

// An error. 150 is an int literal outside -128 to 127 
byte b = 150; 

To make an assignment from int to byte, you must use a cast.

The assignment of num1 to b1 can be rewritten as follows:

b1 = (byte)num1; // Ok 
  

The destination byte variable will always have a value between -128 and 127.

You need to use explicit cast if you want to assign the value of a long variable to a byte variable.

For example,

byte b4 = 1; 
long num3 = 9L; 
  
b4 = (byte)num3;  // OK because of cast 
b4 = 1L;          // Error. Cannot assign long literal to byte 
b4 = (byte)9L;   // OK because of cast 
  

Java class Byte defines two constants to represent maximum and minimum values of the byte data type, Byte.MAX_VALUE and Byte.MIN_VALUE.

byte max = Byte.MAX_VALUE; 
byte min = Byte.MIN_VALUE;

Related Tutorials