- Tutorial: Debug your first Java application
- What Is Debugging?
- Examine the code
- Set breakpoints
- Run the program in debug mode
- Analyze the program state
- Step through the program
- Stop the debugger session and rerun the program
- Java Debugging with Eclipse
- Debugging support in Eclipse
- Step One: Set Breakpoints
- Step Two: Start the Program in Debug Mode
- Step Three: Add Variables to Expressions for Examination
- Step Four: Check the Variables Values in Expressions
- Step Five: Step Into the Function
- Step Six: Step Over
- Step Seven: Check the Return Value from Function
- Step Eight: Set Debug Filter
- Step Nine: Print The Result
- Step Ten: Stop in Main
- Track, Analyze and Manage Errors With Rollbar
Tutorial: Debug your first Java application
You have created and run your Java application. Let’s imagine you have discovered that it functions not the way you expected. For example, it returns a wrong value or crashes with an exception. Seems like you have errors in your code, and it’s time to debug it.
What Is Debugging?
Broadly, debugging is the process of detecting and correcting errors in a program.
There are different kinds of errors, which you are going to deal with. Some of them are easy to catch, like syntax errors, because they are taken care of by the compiler. Another easy case is when the error can be quickly identified by looking at the stack trace, which helps you figure out where the error occurred.
However, there are errors which can be very tricky and take really long to find and fix. For example, a subtle logic error, which happened early in the program may not manifest itself until very late, and sometimes it is a real challenge to sort things out.
This is where the debugger is useful. The debugger is a powerful tool, which lets you find bugs a lot faster by providing an insight into the internal operations of a program. This is possible by pausing the execution and analyzing the state of the program by thorough examination of variables and how they are changed line by line. While debugging, you are in full control of the things. In this manual we are covering a basic debugging scenario to get you started.
Examine the code
Let’s try a simple debugging case. Imagine we have the following application:
The program is supposed to calculate the average of all values passed as command-line arguments.
It compiles and runs without issues; however, the result is not what one would expect. For instance, when we pass 1 2 3 as the input, the result is 6.0 .
First of all, you need to think about where the suspected error might be coming from. We can assume the problem is not in the print statements. Most likely, unexpected results are coming from our findAverage method. In order to find the cause, let’s examine its behavior in the runtime.
Set breakpoints
To examine how the program operates at runtime, we need to suspend its execution before the suspected piece of code. This is done by setting breakpoints. Breakpoints indicate the lines of code where the program will be suspended for you to examine its state.
- Click the gutter at the line where the findAverage method is called.
Run the program in debug mode
Now let’s start the program in debug mode.
Since we are going to pass arguments for running and debugging the program, make sure the run/debug configuration has these arguments in place.
- Click the Run icon in the gutter, then select Modify Run Configuration .
- Enter arguments in the Program arguments field.
- Click the Run button near the main method. From the menu, select Debug .
Analyze the program state
After the debugger session has started, the program runs normally until a breakpoint is hit. When this happens, the line where the program paused gets highlighted and the Debug tool window appears.
The highlighted line has not been executed yet. The program now waits for further instructions from you. The suspended state lets you examine variables, which hold the state of the program.
As the findAverage method has not been called yet, all its local variables like result are not yet in scope, however, we can examine the contents of the args array ( args is in scope for the main method). The contents of args are displayed inline where args is used:
You can also get information about all variables that are currently in scope in the Variables panel.
Step through the program
Now that we are comfortable with the Debug tool window, it’s time to step into the findAverage method and find out what is happening inside it.
- To step into a method, click the Step Into button or press F7 . Another line gets highlighted in the editor because we advanced the execution point one step forward.
- Continue stepping with Step Over F8 . Notice how it is different from Step Into . While it also advances the execution one step forward, it doesn’t visit other methods like Integer.parseInt() along the way. Let’s keep stepping and see how the local variable result is declared and how it is changed with each iteration of the loop. Right now the variable s contains the value «3» . It is going to be converted to int and be added to result , which currently has the value of 3.0 . No errors so far. The sum is calculated correctly.
- Two more steps take us to the return statement, and we see where the omission was. We are returning result , which has the value of 6.0 , without dividing it by the number of inputs. This was the cause of incorrect program output. To continue the program execution after it has been suspended, press F9 or select Run | Debugging Actions | Resume from the main menu.
- Let’s correct the error:
Stop the debugger session and rerun the program
In order to check that the program works fine, let’s stop the debugger session and rerun the program.
- Click the Stop button or press Ctrl+F2 .
- Click the Run button near the main method. From the menu, select Run .
- Verify that the program works correctly now.
Java Debugging with Eclipse
Debugging is the process of identifying and fixing any issues in the source code of a program. Modern IDEs like Eclipse provide debugging tools that make it easier for developers to walk through their code interactively and inspect it to spot and resolve any issues.
Debugging support in Eclipse
Eclipse allows running an application in Debug mode which helps with stepping through each line of code in a program. Eclipse also provides a Debug Perspective which is a set of views grouped together that help inspect code and make the debugging process very effective.
Let’s walk through the steps of debugging a Java application with Eclipse using a simple program, as shown below:
public class EclipseDebuggingExample < public int add(int a, int b) < int result = a + b; return result; >public static void main(String[] args) < EclipseDebuggingExample ede = new EclipseDebuggingExample(); int a = 3; int b = 7; int result = ede.add(a, b); System.out.printf("%d + %d = %d", a, b, result); >>
Two simple methods main() and add() are defined in the above code example. The main() method calls the add() method to add two integers a and b and return their sum. The steps for debugging this program are shown below:
Step One: Set Breakpoints
A breakpoint is a point in code where the program execution pauses during debugging. This allows the programmer to inspect code and the flow of execution at the defined breakpoint.
To define a breakpoint, either double click on the left margin in the editor or right click and select Toggle Breakpoint:
A blue circle should then appear next to the line:
Step Two: Start the Program in Debug Mode
To debug the application, either right-click on the file in Package Explorer or within the Java editor and select Debug As -> Java Application:
Eclipse asks if you want to switch to the Debug Perspective when a breakpoint is reached:
If you click Switch, Eclipse opens this perspective, which has a group of views that help with the debugging process:
The most commonly used views are described below:
- Debug: Displays the call stack which helps in determining the flow of execution of the program until the breakpoint is reached
- Variables: Displays fields and defined variables in the current stack
- Breakpoints: Shows a list of all breakpoints in the code and enabling/disabling breakpoints
- Expressions: Allows defining custom Java expressions to inspect their values
Eclipse also provides several buttons in the toolbar for controlling the flow of execution of the program:
The most commonly used buttons are described below along with their corresponding keyboard shortcuts:
Feature | Key | Description |
---|---|---|
Resume | F8 | Resumes normal execution of the program until the next breakpoint is reached. |
Step Into | F5 | Executes the current line of code and dives into the next line of code in the program execution. If the current line calls a method, the debugger steps into the method. |
Step Over | F6 | Executes the current line of code and goes to the next line without stepping into any method calls or associated scope (e.g. loops and conditions) of the current line. |
Step Return | F7 | Steps back out of the current method and returns to the caller of the method |
Step Three: Add Variables to Expressions for Examination
Any custom Java expressions (including variables) and their values can be inspected in the Expressions view. For example, to track the value of the a , b and the result variables, they can be added to the Expressions view by right-clicking on each and then clicking Watch:
Step Four: Check the Variables Values in Expressions
The variables are now visible in the Expressions view:
The a and b variables show their correct value in the Expressions view. However, since the result variable isn’t declared at this point, it shows an error in the Value column. This should show a proper value after the current line of code is executed.
Step Five: Step Into the Function
Press F5 or the Step Into icon to enter into the add method:
Step Six: Step Over
Press F6 or the Step Over icon to execute the current line of code and go to the next one:
As seen in the image above, the result variable evaluates as expected.
Step Seven: Check the Return Value from Function
Press Step Over again to return to the main() method:
The debugger returns to stop on the same line where it left previously in Step 5. Press Step Over again to check the return value from the add() method:
As expected, the result variable evaluates correctly to the value returned by the add() method.
Step Eight: Set Debug Filter
At this point, if you press Step Into (F5), the debugger will dive into the Java.lang.Integer class:
Because line 12 in the EclipseDebuggingExample class is trying to print out the value of an integer, it calls the valueOf method in the Java.lang.Integer class and the debugger dives in there.
This can be avoided by creating a Step Filter using the following steps:
- In the Debug view, right-click on any item in the pane that contains the daemon thread and select Edit Step Filters:
- In the popup window, check the Use Step Filters box. Enable the packages that you want to filter out and press Apply and Close:
Step Nine: Print The Result
At this point, line 12 executes and prints the result to the Console successfully:
Step Ten: Stop in Main
The debugger can now be stopped by pressing the Terminate icon in the toolbar:
The debugger will now be disconnected:
Track, Analyze and Manage Errors With Rollbar
Managing and debugging issues in your code is challenging. It can make deploying production code an unnerving experience. Rollbar can track and debug Java bugs as well as analyze and manage errors in real-time to help you to proceed with more confidence. Try it today!
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»