The Complete Cycle of Writing, Testing, and Fixing Java Code

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 1.4 Free with a free account

The Complete Cycle of Writing, Testing, and Fixing Java Code

Data Structures and Algorithms · Chapter 1: Getting Started with JavaSection 1.4 · lesson 4 of 8712 min · free with a free account

← Automating Repetitive Tasks Using Conditional Looping MechanismsNext lesson: Designing Program Logic Before Writing Any Code →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Find and fix syntax, runtime and logic errors in Java programs.

  • Describe the edit, compile, run and test cycle and why small steps help
  • Distinguish syntax, runtime and logic errors and read compiler messages and stack traces
  • Use tracing, debug prints and a debugger's breakpoints and step controls
  • Design test cases with expected results and rerun them after every fix

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,721 words). Read along, or search it.

Opening Question

Sum to Four Prints Six

Sum to four should add one, two, three and four, and give back ten. Run it, and it prints six. No error, no warning. Nobody writes a program that works perfectly the first time, not beginners, and not people who've coded for decades. What separates a calm programmer from a frustrated one isn't the number of mistakes. It's the routine used to find and fix them. This lesson builds that routine, and fixes this method.

Workflow

Edit, Compile, Run, Test

Writing and running are separate steps in Java, so programming falls into a loop of four. Edit: type or change the source file, in an editor or an IDE. Compile: java c checks the code and translates it. That's where syntax errors show up. Run: java starts the compiled program. A runtime error stops it, with a report. Test: compare the result with what you expected. Logic errors show up only here, with no message at all. Then go around again. An IDE bundles all four behind its buttons. The most valuable habit is small steps. Type fifty lines before compiling, and a typo hides among fifty suspects. Type five, and there are five.

Classification

Three Families of Bugs

Programmers call any flaw a bug, and bugs come in three families. The family is decided by when the problem shows itself. A syntax error appears before the program starts: the compiler refuses. A runtime error appears while it's running: it starts, then stops. And a logic error appears only after it finishes: the answer is simply wrong.

Syntax Errors

Reading a Compiler Error Message

Syntax is a language's grammar: where semicolons go, how braces pair up, how words are spelled. This program is missing one semicolon, on line three. The compiler can't make sense of it, so it prints a message, and produces no new program. Nothing runs. The message has a fixed shape. The file and line number, then the complaint, semicolon expected. Then a copy of the line, with a caret where the compiler noticed the trouble. Read it like a map reference: this file, this line, this place, this complaint.

Common Messages

Cannot Find Symbol and Other Complaints

The compiler also rejects some mistakes of meaning, like using a name that was never declared. They show up at the same moment, so they're lumped in with syntax errors. Here, count was declared, but capital Count is used. Cannot find symbol: a misspelling, wrong capitals, or a name never declared. Beginners meet a few more often. Possible lossy conversion means a decimal is going into a whole-number variable. Reached end of file while parsing means a closing brace is missing. Missing return statement means a method promised a result, but one path never gives one. And one slip can set off several messages, so fix the first one first, and recompile.

Runtime Errors

Reading a Stack Trace

A runtime error is one the compiler couldn't predict. The code is fine grammatically, so it compiles and starts. Then it's asked to do something impossible. Here the bill of one hundred twenty is split among zero people. Run it, and Java stops on the spot, with a report called a stack trace. The first line says what went wrong: an arithmetic exception, divide by zero. The line starting with at says where: the method, the file, line five. Each pays was never printed: the crash came first. And notice that line five is where the program gave up. The real cause is the zero stored on line four. Other exceptions are read the same way: the first line for what, the first at line for where.

Logic Errors

An Average That Prints Seven

A logic error is the quietest kind, and the most troublesome. The program compiles, runs to the end, and prints a confident answer, which is wrong. This should print the average of seven and eight. It prints seven point oh. A plus b is fifteen, and two is a whole number too. So Java divides whole numbers, and keeps only the seven. Stored in a double, that's seven point oh. Divide by two point oh instead, and Java divides as decimals: seven point five. Nothing in the first output warned us. Only comparing it with the expected value did.

Quick Check

Percentage Score That Prints Zero

Quick check, with a new program. A student got eighteen right out of twenty, and this program reports the score as a percentage. What does it print? Pause, and predict. It prints zero point zero percent. Eighteen over twenty is whole-number division: zero. Zero times a hundred is still zero. That's a logic error: no message anywhere. Ninety would need decimal division. Write a hundred point zero first, and it prints ninety point zero.

Tracing

Hand-Tracing the Sum Loop

Back to sum to four. When no message helps, play the part of the computer. Follow the code one line at a time, and write down every variable. That's tracing. Sum starts at zero. Pass one: i is one, sum is one. Pass two: sum is three. Pass three: sum is six. Then i becomes four, and the test, four less than four, is false. The loop ends before adding four. The method returns six, short by exactly the last term. Tracing has one trap. Follow what the code says, not what you meant. A trace that assumes the loop reaches four proves nothing.

Print Debugging

Temporary DEBUG Print Lines

Tracing only checks your reading. To watch the real program, make it describe itself. Print debugging adds temporary print lines that show values at chosen moments. Each message starts with DEBUG and a label, so it's easy to spot, and easy to remove later. Run it. The real program agrees with the trace: i reached three, and the loop finished with n still four.

Best Practices

Habits for Useful Debug Prints

A few habits make printing far more useful. Label every value: a bare six means nothing, but sum equals six does. Print before and after a suspicious line, to see what it did. In a long program, search by halving: print near the middle, and the values show which half holds the bug. Inside a loop that runs thousands of times, limit the flood to the first few passes. And clean up: delete the debug lines once the bug is fixed.

Debugger

Pausing at a Breakpoint

Printing means editing, recompiling, and rerunning for every new question. A debugger answers questions while the program runs. IntelliJ, Eclipse, and Visual Studio Code all include one. Its key idea is the breakpoint: a marker that pauses the program just before a line runs. Picture one on line five, during the third pass. Frozen there, the variables show n is four, i is three, and sum is three: one plus two. The call stack shows sum to was called from main. Step over runs one line. Sum becomes six. Then i becomes four, the test fails, and the highlight jumps to the return, without line five running a fourth time.

Debugger Controls

Step Over, Into, Out and Resume

Four controls move a paused program forward. Step over runs the current line, and pauses on the next. Step into enters a method being called, and pauses on its first line. Step out finishes the current method, and pauses where it was called. Resume runs at full speed, to the next breakpoint. A conditional breakpoint pauses only when a condition is true, like i equals three. That helps when only one pass in hundreds matters. Prints are quick, work anywhere, and record the whole run. A debugger needs no code changes, and shows every variable at one moment. Use each where it fits.

Quick Check

Tracing a Step-of-Three Loop

Quick check: trace a new loop by hand. Total starts at zero, and i starts at one, goes up by three, and runs while it's less than ten. What's the final total? Pause, and predict. Twelve. Pass one adds one. Pass two adds four. Pass three adds seven: twelve. Then i becomes ten, and ten less than ten is false. Twenty-two would add the ten too. That's tracing what you meant, not what the code says.

Testing

Test Cases With Expected Results

Looking at output and thinking, that seems right, is how logic errors survive. A test case pairs an input with the result you expect, decided before you look. Run the faulty average on more pairs. Seven and eight should give seven point five, and give seven point oh. Fail. Four and four give four point oh. Pass. One and two should give one point five, and give one point oh. Fail. The passing pairs are the ones with an even total, where whole-number division loses nothing. Test only those, and the program looks perfect. A passing test shows that one input works. It never proves the code is right.

Choosing Cases

Typical, Smallest, Zero and Larger

So choose cases with care. For sum to, a typical case: four should give ten. The smallest real case: one should give one. A zero case, where nothing should happen: zero gives zero. And a larger case, ten gives fifty-five, to check the pattern holds.

Self-Testing Code

A Check Method That Reports Pass or Fail

Typing inputs gets tiring, so a program can run its own tests. Check compares an expected value with the actual one, and prints pass or fail with a label. Main calls it once per case, using the same faulty sum to. Run it: zero passes, and the other three fail. Read the pattern, not just the verdicts. Each failure is short by exactly n: six instead of ten, forty-five instead of fifty-five. The last term is being left out. Change less than to less than or equal, recompile, and rerun every test, not just the ones that failed. A fix can break something that used to work. All four pass.

Full Cycle

Fixing Sum to Four End to End

That's the whole cycle. Tests failed, each short by n. A trace and debug prints showed the loop stopping one pass early, and the debugger confirmed it. One edit changed less than to less than or equal. It compiled cleanly, every test was rerun, and all of them passed. Professional teams use testing libraries, such as J Unit, to run thousands of checks like these after every change.

Key Takeaways

Errors, Debugging Tools and Tests

To sum up. Programming is a loop: edit, compile, run, test. Go around it often, changing one thing at a time. Syntax errors stop the compiler, runtime errors stop the program, and logic errors stop nothing, but give a wrong answer. A message gives the file, line and complaint. The real cause may be earlier. And trace, print, or debug to see what really happens. Then test typical, smallest, and zero cases, after every fix.

Think About It

Nine Errors After Forty Lines

Something to think about. After typing forty lines, a programmer compiles and sees nine error messages. What's the best way forward? And what habit would have prevented it?

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About The Complete Cycle of Writing, Testing, and Fixing Java Code

What is the difference between syntax, runtime and logic errors in Java?
They differ by when the problem shows itself. A syntax error is caught by the compiler, so no program is produced and nothing runs. A runtime error appears while the program runs: it compiles and starts, then stops with an exception, such as an ArithmeticException for dividing an int by zero. A logic error lets the program finish, but its answer is wrong and no message appears.
How do you read a Java stack trace?
Read the first line for what went wrong and the first line starting with at for where it happened. The first line names the exception, such as an ArithmeticException for division by zero, and the at line gives the method, file and line number where the program stopped. That line is where Java gave up, not always the real cause, which may be a bad value stored earlier.
What is a breakpoint in a Java debugger?
A breakpoint is a marker that pauses a running program just before a chosen line runs, so you can inspect every variable and the call stack at that moment. From there, step over runs the current line, step into enters a called method, step out finishes the current method, and resume runs to the next breakpoint. A conditional breakpoint pauses only when a condition, such as i == 3, is true.
Why can a program pass a test and still have a bug?
A passing test shows only that one input works, so it never proves the code is right. An average written as (a + b) / 2 with int values passes for 4 and 4 but gives 7.0 instead of 7.5 for 7 and 8. Choose typical, smallest, zero and larger cases with expected results decided in advance, and rerun every test after a fix, because a fix can break something.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Data Structures and Algorithms.

87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →