Bird
Raised Fist0

Identify the error in this Java Kafka producer code snippet:

medium📝 Debug Q14 of Q15
Kafka - with Java/Python
Identify the error in this Java Kafka producer code snippet:
import java.util.Properties;
import org.apache.kafka.clients.producer.*;
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

KafkaProducer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("my-topic");
producer.send(record);
producer.close();
AProducer not closed properly
BIncorrect serializer class name
CMissing bootstrap.servers property
DProducerRecord missing key argument
Step-by-Step Solution
Solution:
  1. Step 1: Check ProducerRecord constructor usage

    The constructor used has only topic, but the generic type expects key and value.
  2. Step 2: Identify mismatch in arguments

    ProducerRecord<String, String> expects key and value, but no key/value is provided, causing a compile error.
  3. Final Answer:

    ProducerRecord missing key argument -> Option D
  4. Quick Check:

    ProducerRecord requires key and value [OK]
Quick Trick: ProducerRecord needs key and value if generics specify both [OK]
Common Mistakes:
MISTAKES
  • Using wrong ProducerRecord constructor
  • Ignoring generic type mismatch
  • Assuming value-only constructor works with key type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kafka Quizzes