Debugging a Java Program With Eclipse
Creating a Java Project
When Eclipse is first started, it is in the Resource perspective, a set of panes for managing projects, folders, files, and other resources. In Eclipse parlance, each of these panes is called a view, and a complete set of views is called a perspective. In the Resource perspective, you can navigate or create resources by using the view at the top left, the Navigator view.
Before you can do anything else in Eclipse, such as creating a Java program, you need to create a Java project. To create a new Java project, follow these steps:
Creating a Java class
Once you've created a project for it to live in, you can create your first Java program. Although doing so is not necessary, it's a good practice to organize your Java classes into packages. It's conventional to use a domain name as the package name because this reduces the likelihood of name collisions-that is, more than one class with exactly the same name. You can use a registered domain name if you have one, but if not, you can use any convenient, unique, ad hoc name, especially for private use.
Follow these steps to create your Java program:
The code that's automatically generated includes a method stub for main(). You need to add any functionality, such as printing your "Hello, world!" yourself. To make debugging more interesting, you'll add a separate method with a loop to print. Alter the code generated by Eclipse as follows:
Running the Java Program
You're now ready to run this program. There are several things you might want to consider when running a Java program, including the Java runtime it should use, whether it will take any command-line parameters, and, if more than one class has a main() method, which one to use. The standard way to start a Java program in Eclipse is to select Run->Run from the Eclipse menu. Doing so brings up a dialog box that lets you configure the launch options for the program; before running a program, you need to create a launch configuration or select an existing launch configuration.
You may wonder why no separate step is required to compile the .java file into a .class file. This is the case because the Eclipse JDT includes a special incremental compiler and evaluates your source code as you type it. Thus it can highlight things such as syntax errors and unresolved references as you type. (Like Eclipse's other friendly features, this functionality can be turned off if you find it annoying.) If compilation is successful, the compiled .class file is saved at the same time your source file is saved.
Debugging the Java Program
Eclipse's ability to run the code interactively is one of its most powerful features. By using theJDT debugger, you can execute your Java program line by line and examine the value of variables at different points in the program, for example. This process can be invaluable in locating problems in your code.