Using a Debugger Core Java

Debugging with print statements is not one of life’s more joyful experiences. You constantly find yourself adding and removing the statements, then recompiling the program. Using a debugger is better. A debugger runs your program in full motion until it reaches a breakpoint, and then you can look at everything that interests you. Listing below show a deliberately corrupted version of the ButtonTest program. When you click on any of the buttons, nothing happens. Look at the source code button clicks are supposed to set the background color to the color specified by the button name.

BuggyButtonTest.java

In a program this short, you may be able to find the bug just by reading the source code. Let us pretend that scanning the source code for errors is not practical. We show you how to use the Eclipse debugger to locate the error.

In Eclipse, start the debugger with the menu option Run -> Debug As -> Java Application. The program will start running.

Set a breakpoint at the first line of the actionPerformed method: Right-click in the left margin, next to the line of code, and chose Toggle Breakpoint. The breakpoint will be hit as soon as Java starts processing code in the actionPerformed method. For this, click on the Yellow button. The debugger breaks at the start of theactionPerformed method.

Stopping at a breakpoint

Stopping at a breakpoint

There are two basic commands to single-step through a program. The “Step Into” command steps into every method call. The “Step Over”command goes to the next line without stepping inside any further method calls. Eclipse uses menu options Run -> Step Into and Run -> Step Over, with keyboard shortcuts F5 and F6. Issue the “Step Over” command twice and see where you are.

Stopping at a breakpoint

That is not what should have happened. The program was supposed to call setColor(Color.yellow) and then exit the method. Inspect the local variables and check the value of the arg variable:

Stopping at a break point

Now you can see what happened. The value of arg was "Yellow", with an uppercase Y, but the comparison tested

To quit the debugger, select Run -> Terminate from the menu. There are more advanced debugging commands in Eclipse, but you can get a long way with the simple techniques that you just saw. Other debuggers, such as the NetBeans debugger, have very similar commands.

This section introduced you to exception handling and gave you some useful hints for testing and debugging. The next two sections cover generic programming and its most important application: the Java collections framework.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics