Easy
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.
Medium
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 + bis automatically promoted toint- Casting back to
byteis required, otherwise an error is thrown 30fits 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
NumberFormatExceptionif 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
Hard
Convert Numbers to Binary
Convert the following numbers to binary:
- 19
- 55
- 20
Show answer:
10011 // 19
110111 // 55
10100 // 20
Leave a Reply