Given the following Kafka custom serializer code snippet, what will be the output byte array when serializing the string "abc"?
public class CustomStringSerializer implements org.apache.kafka.common.serialization.Serializer<String> { @Override public byte[] serialize(String topic, String data) { if (data == null) return null; byte[] originalBytes = data.getBytes(); byte[] result = new byte[originalBytes.length + 1]; result[0] = (byte) originalBytes.length; System.arraycopy(originalBytes, 0, result, 1, originalBytes.length); return result; } }
Think about how the length of the string is stored in the first byte.
The serializer prepends the length of the string as the first byte, then copies the original bytes. For "abc", length is 3, ASCII codes are 97, 98, 99.
Consider this Kafka custom deserializer snippet. What error will occur if data is null?
public class CustomStringDeserializer implements org.apache.kafka.common.serialization.Deserializer<String> { @Override public String deserialize(String topic, byte[] data) { int length = data[0]; return new String(data, 1, length); } }
What happens if you try to access an element of a null array?
If data is null, accessing data[0] causes a NullPointerException.
Choose the most accurate description of what a custom SerDes (Serializer/Deserializer) does in Kafka.
Think about how Kafka sends and receives data as bytes but applications use objects.
Custom SerDes convert between bytes and objects so Kafka can store and transmit data while applications can work with meaningful types.
Given this deserializer code, why might the output strings be incorrect or corrupted?
public class FaultyDeserializer implements org.apache.kafka.common.serialization.Deserializer<String> { @Override public String deserialize(String topic, byte[] data) { if (data == null) return null; int length = data[0]; return new String(data, 0, length); } }
Check the substring start index and length used in the String constructor.
The code uses new String(data, 0, length), which includes the first byte (length byte) as a character, corrupting the output.
Assume a custom deserializer converts a byte array representing multiple key-value pairs into a Map<String, Integer>. The byte array encodes 3 pairs: {"a":1, "b":2, "c":3}. After deserialization, how many entries does the map contain?
byte[] data = new byte[]{3, 97, 1, 98, 2, 99, 3}; // Custom format: first byte count, then pairs of (keyByte, valueByte)
// Deserializer logic:
// int count = data[0];
// for i in 0..count-1:
// key = String.valueOf((char) data[2*i+1]);
// value = data[2*i+2];
// map.put(key, value);Count how many key-value pairs the first byte indicates and how the loop processes them.
The first byte is 3, indicating 3 pairs. The loop runs 3 times, adding 3 entries to the map.