byte Exercises

Declare and Assign

Declare a byte variable named age and assign it the value 21

Show answer:
byte age = 21;

Byte Range Check

What is the output of the following?

System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
Show answer:
-128 // minimum byte value
127 // maximum byte value

Valid or Invalid?

Which of the following assignments are valid? If invalid, explain why.

Show answer:
byte a = 100;   // ✅ Valid
byte b = 128;   // ❌ Invalid. Outside byte range
byte c = -129;  // ❌ Invalid. Outside byte range
byte d = -50;   // ✅ Valid

Replace the Value

What is the final value of x?

byte x = 10;
x = 20;
x = -5;
Show answer:
-5

Primitive variables store only one value at a time. Each assignment replaces the previous value.


Byte arithmetic

What happens when you run this code? Why?

byte a = 10;
byte b = 20;
byte c = (byte) (a + b);
System.out.println(c);
Show answer:
30

Explanation:

  • a + b is automatically promoted to int
  • Casting back to byte is required, otherwise an error is thrown
  • 30 fits in the byte range

String to Byte Conversion

Write code that converts the string "42" into a byte and prints it.

Show answer:
byte value = Byte.parseByte("42");
System.out.println(value);

Explanation:

  • Converts a numeric string into a byte
  • Throws NumberFormatException if invalid or out of range

Compare Two Bytes

Write a program that compares two byte values using Byte.compare() and prints the result.

Show answer:
byte a = 5;
byte b = 10;

int result = Byte.compare(a, b);
System.out.println(result);

Output:

-5

Explanation:

  • Returns a negative number because 5 < 10

Convert Numbers to Binary

Convert the following numbers to binary:

  • 19
  • 55
  • 20
Show answer:

10011 // 19
110111 // 55
10100 // 20


Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories