Sometimes we want our breakpoints to be triggered only under certain conditions. For example, you have a big application with plenty of classes, and when you run it, it gives you unexpected results. If you want to debug such a case, one of the options is to set a breakpoint and track every time certain variables are used, and check the Variables view for the values of these variables. It can take a lot of time, as one method can be called thousands of times. It would be much easier if you could determine the nature of these unexpected results, and trigger a breakpoint only if these results occur. Thus, you should use a conditional breakpoint.
To set up a conditional breakpoint, we will need to make some modifications to our sample program, but first you have to unset the breakpoint from the previous example.
When the breakpoint from the previous example is unset, we will modify our code by performing the following steps:
setPosition()
function (on line 30). Let's comment out the if
statement in this method. Thus we can set any position we like. The setPosition()
function will look like the following:30. public void setPosition (String _position) { 31. // if ( Arrays.asList(validPositions).contains(_position)){ 32. position = _position; 33. //} 34. }
main()
method and change line 112 to the following:andrew.setPosition("");
It means that we are providing an empty string as a position.
position = _position
)._position.isEmpty()
.This means that the breakpoint will be triggered only if _position
is an empty string. Note that, we assign __position
, but not the class variable position
, because at the time the conditional breakpoint is triggered, the position will not be assigned yet.
Your breakpoint should now look like this icon. It means that the breakpoint is only triggered when the condition applies.
Now, as we have set up our conditional breakpoint, let's run the application.
_position
is empty. If _position
were not empty, it would skip this breakpoint and proceed with executing the application. Thus, a conditional breakpoint allows us to trigger the breakpoints only for the cases when we really want the program to stop executing.tester
to setPosition(String)
. Type the following:andrew.setPosition("tester");
This was done to show you that when the position is not empty, the conditional breakpoint is simply skipped.
Now you know how to set up the conditional breakpoint. The condition could be anything you want. It all depends on a particular problem that you are trying to solve.
18.116.80.45