CodeBlanks Logo Icon CodeBlanks

Task model

Design the Task class.

Task model: the Task class

In this project you will build a to-do app step by step. The first step is to define the Task class that represents a task.

Each task has a title (title) and a completion state (done). done is a boolean field; it starts as false.

Task t = new Task("Shopping");
System.out.println(t);
// [ ] Shopping

To print it, we will write a toString method: [x] if done, otherwise [ ]. This lets you see the task state at a glance in the console.

Readable output with toString

In Java, when you print an object with System.out.println, it shows the class name and address by default. If you write a toString method, the object turns into readable text.

public String toString() {
  return (done ? "[x] " : "[ ] ") + title;
}

Here the ternary operator (cond ? a : b) yields [x] when done is true, otherwise [ ] . Then the title is appended. So println(t) prints [ ] Shopping.

Practice Define the Task class

Define the Task class: String title and boolean done fields, a Task(String title) constructor (set title, set done to false), and a toString method ("[x] title" if done, otherwise "[ ] title"). In main, create a Task and print it.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    // Create a Task and print it
  }
}

class Task {
  // Define title (String) and done (boolean) fields
  // Constructor: set title, set done to false
  // toString: "[x] title" if done, otherwise "[ ] title"
}

Sample solution

Main.java
class Task {
  String title;
  boolean done;
  Task(String title) {
    this.title = title;
    this.done = false;
  }
  public String toString() {
    return (done ? "[x] " : "[ ] ") + title;
  }
}
// inside main:
Task t = new Task("Shopping");
System.out.println(t);

Expected output

[ ] Shopping

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the done field when a Task is freshly created?

  • 0
  • true
  • null
  • false Correct answer

Explanation: A new task is not yet done, so done is false.

2 Fill in the blank: Task field

Question
class Task {
  String title;
  ____ done;
}
Answer
class Task {
  String title;
  boolean done;
}

Explanation: done should be a primitive boolean.

3 Match field to initial value

Term Meaning
title comes from the parameter
done false
ArrayList<Task> empty list
int index starts at 0

All lessons in Beginner