Course Content
Java OOP
Java OOP
Debugger
What is debugger?
A debugger is a tool that helps you step through your code. We can pause the execution of the code at a certain point and start the debugging mode to see how our code is functioning. To do this, we need to set a marker (breakpoint) on the line where we want to pause.
We have a code that should calculate the sum of numbers from one to ten, inclusive. The result should be 55
, but we are getting 45
as the answer. Let's set a breakpoint at the beginning of the loop to understand why the answer doesn't match. To do this, you need to click the left mouse button on the line number, and a red marker will appear there.
Instruments inside the debug mode
Let's briefly look at how to work with the debugger and what tools are available inside it.
- Step Over: With this button, we can continue the code execution one line at a time. When pressed, the debugger will execute the current line and move to the next one, and then stop again;
- Step Into: With this button, we can enter into the execution of a method. In our example, there is no method, but if there were one, we would be able to step inside it and see what is happening there;
- Step Out: This button is the opposite of the previous one. It allows us to exit the execution of a method or loop;
- We can see the values of variables in the window at the bottom or next to these variables. We can clearly see the value of the variable
result
, which initially equals zero.
Iterating through the code
To iterate, let's click on the "Step Over" button. We enter the for
loop, and the value of the variable i
appears, which is created inside the for
loop. Initially, we set this variable to zero.
Next, we click "Step Over" several times to complete one iteration and move to the console to see if anything is printed on the screen. We can see that the variable i
increased by 1
, and "0" was displayed on the screen, as both the result
variable and the i
variable were initially set to zero. 0 + 0 = 0
-> this is what was displayed on the screen.
Let's skip the iterations of printing the other numbers to the console and go to the end. It is here that we can see the main mistake in our loop. We need to display the sum of numbers from 0 to 10 inclusive, but we did not include 10. Therefore, when we see that i = 9
and when it is increased to 10
, we exit the loop since 10 !< 10
(10 is not less than 10).
To solve this problem, we need to change the condition to i <= 10
. Then we will get the correct result.
In essence, we repeatedly pressed the "Step Over" button several times, leading us to the realization of the loop's mistake and the subsequent correction.
Note
I have shown only the basic debugger tools. To learn how to use them, you should practice with it yourself. You can write a similar program and independently see how everything works. The debugger is a very useful tool because it helps to work on errors and bugs in the code.
Thanks for your feedback!