Looking at Variables

The Eclipse IDE provides many different ways to examine and modify your program state. For example, as you single step, you may have noticed that the Variables window shows the current value of all the local variables, parameters, and fields that are currently visible (see Figure 19). You can quickly identify which variables are changing because Eclipse draws them in a different color. If any of the variables are nonprimitives (objects or arrays), you can expand them to look at the individual elements.

To change the value of a variable, first select it in the Variables view. This will make its current value appear in the bottom half of the window, where you can change it. Save the new value by pressing Ctrl+S (or right-click and select Assign Value).

The Variables view shows all the values in scope. Changes since the last step or resume are highlighted in red.

Figure 4-3. The Variables view shows all the values in scope. Changes since the last step or resume are highlighted in red.

Tip

When you are coding, try to use the smallest possible scope for your local variables. For example, instead of declaring all your variables at the top of a function, declare them inside the statement blocks (curly braces) where they are actually used. Besides being a good programming practice, this will limit the number of items displayed in the Variables view.

Another way to see the value of a particular variable is to move your cursor over it in the source editor. After a short pause, a tool tip window will appear with the value. See Figure 20 for an example.

Hover the mouse over a variable in the Java editor to see its current value.

Figure 4-4. Hover the mouse over a variable in the Java editor to see its current value.

What if you need to see the value of a Java expression? No problem: just use the mouse or keyboard to select the expression in the editor, then press Ctrl+Shift+D (or right-click and select Display). Eclipse will evaluate the expression (including any side effects) and show the results in a pop-up window (see Figure 21). The expression can be as simple or as complicated as you like, as long as it's valid.

Select an expression and press Ctrl+Shift+D to evaluate it.

Figure 4-5. Select an expression and press Ctrl+Shift+D to evaluate it.

For compound objects like class instances, you may want to try the Inspect command (Ctrl+Shift+I, or right-click and select Inspect) instead of Display. This will let you expand items and collapse members as in the Variables view.

Get Eclipse IDE Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.