IntelliJ IDEA 2023.3 Help

Tutorial: Set value

From this tutorial, you will learn how to use one of the most basic, but very useful debugger features: Set Value.

While debugging, you get the information about your variables and examine them in order to understand why a program behaves in a particular way. Other times, you would want to reproduce some bug, which depends on some variable. To do that, you would need this variable to hold a particular value.

Reproducing some conditions without modifying the program at runtime may be tedious and time-consuming, so most of the time you would benefit from setting the variable value right from the debugger.

Problem

Let's look at the following simple program:

import java.util.*; class Aquarium { private ArrayList<Fish> fish; public static void main(String[] args) { var aquarium = new Aquarium(); System.out.println(aquarium.getFish()); // fish has already been initialized System.out.println(aquarium.getFish()); // line n1 } private ArrayList<Fish> getFish() { if (fish == null) initFish(); return fish; } private void initFish() { fish = new ArrayList<>(Arrays.asList( new Fish("Bubbles"), new Fish("Calypso"), new Fish("Dory") )); } } class Fish { private String name; Fish(String name) { this.name = name; } public String toString() { return name; } }

In this code we have an instance variable (fish) that is printed out twice. The getter of the fish variable employs lazy initialization, which means the object is only initialized when it is first needed.

Now what if fish has already been initialized (suppose we are at line n1), and we want to look into the initFish method? This method will only be executed if (fish == null) evaluates to true.

In this simple case we could just put a breakpoint in the method and restart the session. In more complex cases, however, you may find it very inconvenient to restart the session and perform all the steps that lead to a certain state. Now let's learn the smarter way.

Solution

So, we are at line n1, and we need to step through the ArrayList initialization in the initFish method.

  1. Put a breakpoint in the initFish method.

    Breakpoint in the initFish method
  2. On the Variables tab, expand aquarium, right-click fish, and select Set value.

    The array on the Variables tab
  3. Enter null. Press Enter.

    Setting the reference to null
  4. Press F9 to resume the debugger session.

Now the condition evaluates to true, and we can step through the initFish method and see how it performs the initialization.

Summary

The example in this tutorial illustrated how you can modify the variables at runtime to change the flow of your program. Although the example is very simple, you can apply the same principle in more complex projects, where this feature will save you a lot of time.

Last modified: 11 February 2024