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:
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
According to the problem statement, suspend the program at
line n1
Set a breakpoint in the
getFish()
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 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.