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 on the values of 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:
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.
Put a breakpoint in the
initFish
method.On the Variables tab, expand
aquarium
, right-clickfish
, and select Set value.Enter
null
. Press Enter.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.