The byte keyword has following two usages in Java:
- byte data type
- byte return type of a method
The byte keyword is used to define a primitive data type. A byte data type variable can hold values ranging from -128 to 127. The size of byte data type is 8 bit.
It can also be used as a return type of a method.
byte Keyword Examples
Example 1:
class JavaExample { public static void main(String args[]) { byte num = 100, num2 = -50; System.out.println(num); System.out.println(num2); } }
Output:
100 -50
Example 2:
This program will throw error as the max value that a byte data type can handle is 127
and the minimum value it can handle is -128
.
class JavaExample { public static void main(String args[]) { byte num = 200; System.out.println(num); } }
Output:
Example 3:
In this example, we have a method with byte return type. This method takes int argument as input and returns byte equivalent, if input value falls in the valid byte range.
class JavaExample { public static byte myMethod(int num){ byte bVar; if(num<=127 || num>=-128){ bVar = (byte)num; //type casting }else{ System.out.println("Byte can only hold values between -128 to 127"); bVar = 0; } return bVar; } public static void main(String args[]) { int num = 101; System.out.println("Given int to byte: "+myMethod(num)); } }
Output:
Given int to byte: 101