IntelliJ IDEA 2024.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. It employs lazy initialization, which in our case means that the field is not assigned a value until its getter is called.

Consider the situation when you have already stepped to line n1, and fish has already been initialized, but you want to look into the initFish method? This method will only be executed if (fish == null) evaluates to true, which is no longer the case at line n1.

With this simple program, we could just restart the session. However, in more complex cases, you may find it very inconvenient to relaunch the session and reproduce the steps that lead to a certain state. Let's learn the smarter way.

Solution

  1. According to the problem statement, suspend the program at line n1

    The program is suspended at line n1 – the last line of the main() method
  2. Set a breakpoint in the getFish() method.

    Breakpoint in the getFish() method
  3. On the Variables tab, expand aquarium, right-click fish, and select Set value.

    The 'fish' list on the Variables tab
  4. Enter null. Press Enter.

    Setting the 'fish' field to null
  5. Press F9 to resume the debugger session.

Now the condition evaluates to true, and we enter the initFish method once again, which allows us to see how it performs the initialization.

Summary

This scenario illustrates 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: 23 October 2024