CodeGym /Java Blog /Java Types /Java Byte Keyword
Author
John Selawsky
Senior Java Developer and Tutor at LearningTree

Java Byte Keyword

Published in the Java Types group

What is a “byte”?

8 bits (bit is the smallest unit of data containing at most 2 logical states, normally 0 and 1) combine to make a single unit of addressable memory, called a “Byte”. Here’s a theoretical representation of what a byte normally looks like.Java Byte Keyword - 1

Fig 1: A normal representation of a Byte

What is a Java byte?

A Java byte with small “b” is used to define the primitive data type, that is capable of storing 8 bits at a time. Hence the numeric range of a byte spans from -2^7 = -128 upto +2^7-1 =127. Have a look at the following illustration to have a better understanding of how we can compute this range.Java Byte Keyword - 2

Fig 2: Min and Max Values in a normal 8-bit Byte

What is a Java Byte?

Java Byte is a wrapper class used to store the primitive data type “byte” for easier access to built-in advanced functions. Let’s have a look at a basic example of storing numeric values in bytes and see how it works.

package com.bytekeyword.core;
public class ByteInJava {

	public static void main(String[] args) {

		// declare the variable and assign a valid numeric value
		byte barCode = 112;		
		byte areaCodeNY = 98;
		byte areaCodeLA = 97;	
		
            // print the byte values
		System.out.println("barCode: " + barCode);
		System.out.println("areaCodeNY: " + areaCodeNY);
		System.out.println("areaCodeLA: " + areaCodeLA);
	}
}
Output
barCode: 112 areaCodeNY: 98 areaCodeLA: 97

Addition of byte values in Java

Let’s have a look at a brief example for addition of byte values in Java for a better understanding.

package com.bytekeyword.core;
public class SumOfBytes {

	public static void main(String[] args) {

		Byte x = 25;
		Byte y = 4;

		// Addition of 2 Bytes
		System.out.println(x + " + " +  y  + " = " + (x + y));
		
		byte z = 11;
		// Addition of a "Byte" and a "byte"
		System.out.println(z + " + " +  y  + " = " + (z + y));
	}
}
Output
25 + 4 = 29 11 + 4 = 15

Why use “byte” and not “int”?

We can normally use “byte” instead of a primitive integer when there’s a memory or performance constraint. Since 1 integer’s size is equal to the size of 4 bytes so we can conserve memory 4 times as that of a simple integer. This space conservation is extremely helpful when you’re dealing with network programming. Sending a byte in place of an int, can save your memory and bandwidth.

Conclusion

By the end, we hope you have a clear understanding of the architecture level of byte along with its regular java functionality. However, if you get blocked while practising, feel free to consult this article again. Good luck and happy learning!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION