Skip to lesson

Watching variables and evaluating expressions

A ShopLite wallet declines a customer who has exactly enough money, and the code looks right. When the program is paused, you can ask it questions: what is in this list, is this true, what if stock were 0?

The variables view: locals, fields, collections and toString()

The variables view is the part of the debugger that lists everything the paused frame can see: its parameters, its local variables, and this with the object's fields.

Example 1 prints four objects. The variables view shows the same objects: a plain class as its class name and an id, a record as readable text, and a list or map with its size.

Example 1 · What the variables view shows for objects

ToStringDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;
class PlainOrder {    int id;    int total;
    PlainOrder(int id, int total) {        this.id = id;        this.total = total;    }}
record OrderLine(String sku, int quantity, int unitPrice) {}
public class ToStringDemo {    public static void main(String[] args) {        PlainOrder plain = new PlainOrder(17, 3097);        OrderLine line = new OrderLine("BK-CLEAN", 1, 499);        List<OrderLine> lines = List.of(line, new OrderLine("ACC-AD141", 2, 1299));        Map<String, Integer> stock = new TreeMap<>(Map.of("BK-CLEAN", 30, "ACC-AD141", 120));
        System.out.println(plain);        System.out.println(line);        System.out.println(lines.size() + " lines: " + lines);        System.out.println(stock);    }}
Sample output
PlainOrder@76ed5528
OrderLine[sku=BK-CLEAN, quantity=1, unitPrice=499]
2 lines: [OrderLine[sku=BK-CLEAN, quantity=1, unitPrice=499], OrderLine[sku=ACC-AD141, quantity=2, unitPrice=1299]]
{ACC-AD141=120, BK-CLEAN=30}

What this code does

  • PlainOrder has no toString(), so printing it gives the class name and a hash code that changes per run. The debugger shows it the same way, and you must expand it to see id and total.
  • The record OrderLine gets a generated toString(), so the list and its elements are readable at a glance. The TreeMap keeps its keys sorted, so it prints in the same order every run.

In IntelliJ the view is the right side of the Threads & Variables tab; in VS Code it is the VARIABLES section. Click the arrow to open an object into its fields; a List or Map opens into its elements. In a static method there is no this.

If a class overrides toString(), both IDEs show that text next to the object, like Example 1's second line. Without it you see only the class and an id such as PlainOrder@812; the number differs per run.

The debugger calls toString() itself to draw that label. A toString() that changes data or calls a database changes the program while you watch it (Practice 6). IntelliJ can turn this off in Settings → Build, Execution, Deployment → Debugger → Data Views → Java; VS Code has the java.debug.settings.showToString setting.

Watches for values you check repeatedly

A watch is an expression you pin in the debugger. It is evaluated again every time the program pauses, so you see how it changes from pass to pass.

In Example 2 a wallet declines a bill that equals the balance. Pin three watches, balance, bill and balance > bill, and put a breakpoint on the if line.

Example 2 · A wallet that declines an exact balance

WalletDemo.javaJava
public class WalletDemo {    public static void main(String[] args) {        int balance = 300;        int[] bills = {120, 60, 120, 40};        for (int day = 0; day < bills.length; day++) {            int bill = bills[day];            if (balance > bill) {                balance -= bill;                System.out.println("Day " + (day + 1) + ": paid Rs " + bill + ", left Rs " + balance);            } else {                System.out.println("Day " + (day + 1) + ": DECLINED Rs " + bill + ", left Rs " + balance);            }        }    }}
Output
Day 1: paid Rs 120, left Rs 180
Day 2: paid Rs 60, left Rs 120
Day 3: DECLINED Rs 120, left Rs 120
Day 4: paid Rs 40, left Rs 80

What this code does

  • With watches on balance, bill and balance > bill, the pause on day 3 shows 120, 120, false. The condition, not the arithmetic, is wrong.
  • Changing > to >= pays day 3 and leaves Rs 0, so day 4 is declined instead (Practice 2).

On day 3 the watches show 120, 120 and false: the wallet has exactly enough, yet the payment is declined. The test should be balance >= bill.

To add a watch, click + in the variables view (IntelliJ) or in the WATCH section (VS Code), or right-click a variable and choose Add to Watches. A watch can be any expression that is valid on that line, such as cart.size().

Predict the output

Read the watches

The program is paused on the if line. Predict what each watch shows.

Round 1 of 2

balance is 120 and bill is 120. What does the watch balance > bill show?

int balance = 120;
int bill = 120;
// watch: balance > bill
if (balance > bill) {
balance -= bill;
}

Evaluate expression while paused

Evaluate Expression runs one Java expression in the paused frame, with the real variables of that moment, and shows the result. It is the fastest way to test an idea.

Example 3 prints the expressions you would type into Evaluate Expression while paused in discountFor. Each one tests one idea about why the coupon never applies.

Example 3 · Evaluating ideas about a coupon that never applies

CouponEvaluateDemo.javaJava
import java.util.Map;
public class CouponEvaluateDemo {    static final Map<String, Integer> COUPONS = Map.of("FEST20", 20, "WELCOME10", 10);
    static int discountFor(String code) {        Integer percent = COUPONS.get(code);        return percent == null ? 0 : percent;    }
    public static void main(String[] args) {        String code = "FEST20 ";   // what the checkout form sent        System.out.println("Discount: " + discountFor(code) + "%");
        // What you would type into Evaluate Expression while paused in discountFor:        System.out.println("code.length()             -> " + code.length());        System.out.println("COUPONS.get(code)         -> " + COUPONS.get(code));        System.out.println("\"[\" + code + \"]\"          -> " + "[" + code + "]");        System.out.println("COUPONS.get(code.strip()) -> " + COUPONS.get(code.strip()));    }}
Output
Discount: 0%
code.length()             -> 7
COUPONS.get(code)         -> null
"[" + code + "]"          -> [FEST20 ]
COUPONS.get(code.strip()) -> 20

What this code does

  • The program prints the same expressions you would evaluate while paused in discountFor. code.length() is 7 for a 6-letter code, and the brackets make the trailing space visible.
  • COUPONS.get(code.strip()) returns 20, which confirms the cause. The fix belongs where input enters the program: clean the code once, before the lookup (Practice 3).

Open it like this:

  • IntelliJ: Alt+F8 (Option+F8 on a Mac). Select text in the editor first to evaluate just that part.
  • VS Code: type the expression in the DEBUG CONSOLE and press Enter.
  • Hovering over a variable in either IDE shows its value too.

COUPONS.get(code) gives null while COUPONS.get(code.strip()) gives 20: the form sends a trailing space. One evaluation proves the cause before you change any code.

Fix the error

Fix what Evaluate showed

Evaluate showed that code has a trailing space. Pick the line that fixes the lookup.

FEST20 should give 20%, but COUPONS.get(code) is null for "FEST20 ". Fix line 2.

static int discountFor(String code) {
Integer percent = COUPONS.get(code);
return percent == null ? 0 : percent;
}

Error

Discount: 0%   (expected 20%)
Evaluated code really runs. queue.pollFirst() or list.clear() typed into Evaluate changes the program's data for the rest of the run.

Changing a value to test a theory

Set Value changes a variable while the program is paused, and the rest of the run uses the new value. It never changes the source code or the data.

In Example 4 the real stock is 30, so only the last branch ever runs. Pause at the start of checkStock, set stock to 0 and resume: the out-of-stock message appears.

Example 4 · Reaching every branch with Set Value

StockCheckDemo.javaJava
public class StockCheckDemo {    static String checkStock(String sku, int stock, int requested) {        if (stock == 0) {            return sku + ": out of stock";        }        if (requested > stock) {            return sku + ": only " + stock + " left";        }        return sku + ": OK, reserve " + requested;    }
    public static void main(String[] args) {        // The real data only ever reaches the last branch.        System.out.println(checkStock("BK-CLEAN", 30, 2));        // With Set Value you change stock while paused, without touching the data:        System.out.println(checkStock("BK-CLEAN", 1, 2));        System.out.println(checkStock("BK-CLEAN", 0, 2));    }}
Output
BK-CLEAN: OK, reserve 2
BK-CLEAN: only 1 left
BK-CLEAN: out of stock

What this code does

  • The first call is the real data. The second and third calls show what the same run prints after Set Value changes stock to 1 and to 0 at the start of checkStock.
  • This is how you check an error message or a rare branch in a few seconds, before writing a proper test for it.

In IntelliJ, right-click the variable and choose Set Value, or select it and press F2. In VS Code, right-click it and choose Set Value, or double-click the value.

Only this one run changes. The source code, the database and the next run are untouched.

Dropping a frame to rerun a method

Reset Frame (IntelliJ) or Restart Frame (VS Code) throws away the current method call and pauses back at the line that called it, so you can step through the method again.

In Example 5, issueToken changes a static field and a list. Reset its frame and run it again: only the local variables start over, so the rerun issues a second token for Ravi.

Example 5 · What Reset Frame does not undo

ResetFrameDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ResetFrameDemo {    static int tokensIssued = 0;
    static String issueToken(List<String> queue, String student) {        tokensIssued++;                      // changes a field        String token = "T" + tokensIssued;        queue.add(token + ":" + student);    // changes the caller's list        return token;    }
    public static void main(String[] args) {        List<String> queue = new ArrayList<>();        issueToken(queue, "Asha");        System.out.println("After one call:  " + queue);
        issueToken(queue, "Ravi");        issueToken(queue, "Ravi");        System.out.println("After a rerun:   " + queue + ", tokensIssued = " + tokensIssued);    }}
Output
After one call:  [T1:Asha]
After a rerun:   [T1:Asha, T2:Ravi, T3:Ravi], tokensIssued = 3

What this code does

  • issueToken changes a static field and the caller's list. Resetting its frame and running it again has the same effect as calling it twice: Ravi gets T2 and T3.
  • token is a local variable, so it starts over on the rerun. tokensIssued and queue are not local, so they keep the first run's change.

In IntelliJ, right-click the frame in the frames list and choose Reset Frame (older versions call it Drop Frame). In VS Code, hover the frame in CALL STACK and click its restart icon.

Fields, collections, files, database rows and printed output keep every change the first run made. Only the method's local variables start over.

Predict the output

What survives a Reset Frame?

issueToken ran once for Asha. You reset its frame and run it again for Asha.

After the rerun, what are the local token and the list queue?

static int tokensIssued = 0;
static String issueToken(List<String> queue, String student) {
tokensIssued++;
String token = "T" + tokensIssued;
queue.add(token + ":" + student);
return token;
}
The bottom frame (main) has no caller to go back to, so it cannot be reset. For a method with side effects, restart the whole debug session instead.

Next step

Check your understanding

12 quick questions