GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java18 / 25

Introduction to Chatbots and the Legacy of ELIZA

Building your first chatbot in Java

17.1 Learning Objectives

By the end of this chapter, you should be able to:

  • explain the history and evolution of chatbots, from ELIZA to modern systems;
  • implement a basic EchoBot chatbot in Java;
  • use data structures such as Map to store predefined responses;
  • apply input and output concepts to build console-based interactions;
  • understand why personality matters in a chatbot.

17.2 A Brief History of Chatbots

Timeline: from early chatbots to modern AI.

Figure 17.1. Timeline: from early chatbots to modern AI.

Chatbots are not a new idea! The history of conversational software goes back to at least the 1960s:

  • 1966: ELIZA, created by Joseph Weizenbaum at MIT, was one of the first chatbots to simulate human conversation. ELIZA used text pattern matching and pronoun substitution to produce replies that appeared surprisingly intelligent.
  • 1970s–1980s: Simple command-line applications that processed text inputs.
  • 2000s: More sophisticated virtual assistants began to emerge.
  • Today: Modern chatbots that use machine learning and natural language processing (NLP) to understand and generate human language.

What sets a chatbot apart from a plain command-line application is personality. A good chatbot does not merely process commands; it also provides a more natural and engaging interactive experience.

17.3 EchoBot: The Simplest Chatbot

Let’s start with the most basic chatbot possible: EchoBot. It simply echoes back whatever the user types, adding a brief confirmation.

17.3.1 Example 1: The respond() Method

Create a file named EchoBot.java (complete source in EchoBot.java):

public class EchoBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    public static String respond(String message) {
        // Concatenates the user's message with a standard response
        String botMessage = "I can hear you! You said: " + message;
        return botMessage;
    }

    public static void main(String[] args) {
        String userMessage = "Hello!";
        String response = respond(userMessage);
        System.out.println(String.format(USER_TEMPLATE, userMessage));
        System.out.println(String.format(BOT_TEMPLATE, response));
    }
}

Compile and run:

cd examples/src/part3
javac EchoBot.java
java EchoBot

Expected output:

USER: Hello!
BOT: I can hear you! You said: Hello!

17.3.2 Example 2: The sendMessage() Method

Now let’s improve our EchoBot by adding a method that manages the entire message exchange (complete source in ImprovedEchoBot.java):

public class ImprovedEchoBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    public static String respond(String message) {
        return "I can hear you! You said: " + message;
    }

    public static void sendMessage(String message) {
        // Displays the user's message
        System.out.println(String.format(USER_TEMPLATE, message));

        // Gets the bot's response
        String response = respond(message);

        // Displays the bot's response
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        sendMessage("Hello!");
        sendMessage("How are you?");
    }
}

17.4 Adding Personality: Smalltalk

Now let’s evolve from EchoBot into a chatbot that can answer specific questions. We will use a Map to store predefined responses.

17.4.1 Example 3: Chatbot with Predefined Responses

Complete source in SmalltalkBot.java:

import java.util.HashMap;
import java.util.Map;

public class SmalltalkBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    private static final String NAME = "JavaTutorBot";
    private static final String WEATHER = "sunny";

    private static final Map<String, String> RESPONSES = new HashMap<>();

    static {
        RESPONSES.put("what is your name?", "my name is " + NAME);
        RESPONSES.put("what's the weather like today?", "the weather is " + WEATHER);
        RESPONSES.put("default", "default message");
    }

    public static String respond(String message) {
        String lowerMessage = message.toLowerCase().trim();

        // Checks whether the message has a predefined response
        if (RESPONSES.containsKey(lowerMessage)) {
            return RESPONSES.get(lowerMessage);
        } else {
            return RESPONSES.get("default");
        }
    }

    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = respond(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        sendMessage("what is your name?");
        sendMessage("what's the weather like today?");
        sendMessage("what is your favorite color?");
    }
}

17.4.2 Practical Exercise 1

  1. Create an EchoBot class with a respond() method that concatenates "I heard: " with the user’s message.
  2. Add a sendMessage() method that displays both the user’s message and the bot’s response.
  3. Test it with at least 3 different messages.

Completion criteria:

  • The code compiles without errors
  • The respond() method returns the properly formatted string
  • The sendMessage() method displays both messages

17.5 Adding Variety to Responses

Hearing the exact same answer every time gets boring quickly. Let’s add variety by storing lists of possible replies and choosing one at random.

17.5.1 Example 4: Randomized Responses

Complete source in VariedBot.java:

import java.util.*;

public class VariedBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    private static final String NAME = "JavaTutorBot";
    private static final String WEATHER = "sunny";

    private static final Map<String, List<String>> RESPONSES = new HashMap<>();
    private static final Random RANDOM = new Random();

    static {
        // Varied responses for each question
        RESPONSES.put("what is your name?", Arrays.asList(
            "my name is " + NAME,
            "they call me " + NAME,
            "I am " + NAME
        ));
        RESPONSES.put("what's the weather like today?", Arrays.asList(
            "the weather is " + WEATHER,
            "it's " + WEATHER + " today"
        ));
        RESPONSES.put("default", Arrays.asList(
            "I didn't understand, could you repeat that?",
            "sorry, I don't know how to answer that",
            "interesting question! but I don't know the answer"
        ));
    }

    public static String respond(String message) {
        String lowerMessage = message.toLowerCase().trim();

        List<String> possibleResponses = RESPONSES.getOrDefault(lowerMessage, RESPONSES.get("default"));

        // Selects a random response from the list
        return possibleResponses.get(RANDOM.nextInt(possibleResponses.size()));
    }

    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = respond(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        // Test the same question several times to see the variety
        for (int i = 0; i < 5; i++) {
            sendMessage("what is your name?");
        }
    }
}

17.6 Distinguishing Questions from Statements

An important aspect of chatbots like ELIZA is the ability to tell questions apart from statements and reply appropriately to each.

17.6.1 Example 5: Question Detection

Complete source in QuestionBot.java:

import java.util.*;

public class QuestionBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    private static final Map<String, List<String>> RESPONSES = new HashMap<>();
    private static final Random RANDOM = new Random();

    static {
        RESPONSES.put("question", Arrays.asList(
            "I don't know :(",
            "you tell me!"
        ));
        RESPONSES.put("statement", Arrays.asList(
            "tell me more!",
            "why do you think that?",
            "how do you feel about that?",
            "I find that extremely interesting",
            "can you elaborate on that?",
            "wow!",
            ":)"
        ));
    }

    public static String respond(String message) {
        // Checks whether the message ends with a question mark
        if (message.trim().endsWith("?")) {
            return getRandomResponse("question");
        } else {
            return getRandomResponse("statement");
        }
    }

    private static String getRandomResponse(String key) {
        List<String> possibleResponses = RESPONSES.get(key);
        return possibleResponses.get(RANDOM.nextInt(possibleResponses.size()));
    }

    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = respond(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        // Messages ending with ?
        sendMessage("what's the weather like today?");
        sendMessage("what is your name?");

        // Messages not ending with ?
        sendMessage("I love programming chatbots");
        sendMessage("Java is an interesting language");
    }
}

17.7 Project Evolution: Base Version of the Chatbot

In this chapter, we built the foundation of our chatbot:

  1. EchoBot: A simple chatbot that echoes user messages
  2. SmalltalkBot: Adds predefined responses for specific questions
  3. VariedBot: Introduces response variety through random selection
  4. QuestionBot: Distinguishes between questions and statements

These concepts lay the groundwork for the following chapters, where we will add:

  • Phrase extraction using regular expressions (Chapter 2)
  • Pronoun handling and grammatical transformations (Chapter 2)
  • Intents and entities for deeper language understanding (Chapter 3)
  • State management (Chapter 4)

17.8 Verifiable Practice

  1. Implement EchoBot with the respond() and sendMessage() methods.
  2. Modify SmalltalkBot to include at least 5 different questions with predefined responses.
  3. Add at least 3 different responses for each question in VariedBot.
  4. Test QuestionBot with 10 different messages (5 questions and 5 statements).

Completion criteria:

  • All examples compile with javac --release 21
  • Responses match the message type (question or statement)
  • Random selection works properly
  • The code follows Java naming conventions

Before moving on

You should be able to explain:

  • What is the difference between an EchoBot and a chatbot with personality?
  • How do you use a Map to store predefined responses?
  • How do you add variety to responses using lists and random selection?
  • How do you distinguish between questions and statements?

17.9 Additional Resources