Concept Explanation
Debugging in Java becomes much easier when you treat errors as clues instead of surprises. In this lesson, you will inspect a small program, spot why it fails, and fix it without changing the goal of the code. The focus is on reading stack traces, checking assumptions, and making small targeted corrections that keep the program clear and maintainable. By the end, you should feel more comfortable tracing problems in simple Java programs and explaining why the fix works. Lesson fingerprint: java:Java Beginner:Java setup and execution model:beginner-java-setup-and-execution-model-3:3.
Where to Put the Code
- Define color and position variables at the top.
- Create shape drawing or placement logic in the middle.
- Render output (print, canvas, SVG, or styled block) at the end.
Command Reference
- Run the program once with invalid text and once with a clean numeric value.
- Describe the exact reason Integer.parseInt fails in this example.
- Update the code so the message helps the user understand what went wrong.
- Note how this kind of bug appears in forms, config files, and command-line input.
Step-by-step Guide
- Run the starter code and identify the line that can throw an exception.
- Explain in one sentence why the original input is not valid for parsing.
- Replace the fragile part with a safer version that still keeps the code simple.
- Test one valid input and one invalid input to confirm the behavior changed as expected.
- Finish with a short checklist: readable message, no crash, correct output.
Practice Exercises
- Try three different inputs such as "42", "9x", and an empty string, then record the result of each.
- Change the program so it trims spaces before parsing.
- Write a second example that catches a different exception in a realistic way.
Coding Challenges
- Create a helper method that returns either a parsed number or a fallback value.
- Compare handling the error with try/catch versus validating the string before parsing.
Mini Practice Tasks
- Rename the variables so their purpose is obvious at a glance.
- Add one more user-friendly output message.
- Summarize the bug and the fix in a single line.
Common Mistake
Mixing x and y axes or using wrong coordinate origin causes shapes to appear in unexpected places.
Real-life Mini Challenge
Draw one square, one triangle, and one circle, then move X marker 2 steps right and 1 step down.