ITC 120 › Prelim › Programming refresher
Introduction · Lesson 1 of 2
Programming Refresher
A quick Java review before data structures. Skip any part you already know.
By the end, you can:
- read a line like
int score = 92;aloud, and explain what=does; - predict what short code with conditions (
if,else if,&&,||,!), loops (for,while), and methods prints; - make an array in Java and find a value in it by its index (counting from 0);
- trace a loop with a trace table;
- read a complete Java program: where it starts (
main) and what it prints; - tell the three main kinds of errors apart: compile-time, runtime, and logic.
You need: your Programming 1 and 2 notes (if you have them), and scratch paper.
Part 1 · The building blocks
Rebuild the mental model first
Before data structures, let's remember how programs store values, make decisions, repeat work, and reuse code. Every data structure in this course is built and used with these same pieces, so here are the eight things you need.
1Variables are named places for values
Variable
A named place in memory that holds one value. Its type says what kind of value it can hold.
String name = "Ana";
int score = 92;
double average = 85.0;
boolean passed = true; Read each line as type name = value. The type says what kind of value fits: int for whole numbers, double for decimals, boolean for true or false, String for text. A clear name (score, not s) tells the reader what the value means.
2Assignment stores; expressions calculate
int x = 5; // x starts at 5
x = x + 2; // x becomes 7
int total = x * 3; // total becomes 21 x = x + 2: Java works out the right side first, then stores the result in x.The = sign is assignment: "work out the right side, then store the result in the variable on the left." It does not mean "is equal to." That is why x = x + 2 makes sense: take the old x (5), add 2, and store 7 back in x.
Expression
Anything Java can work out to one value, such as x + 2 or x * 3.
These operators build expressions:
| Operator | Meaning | Example |
|---|---|---|
+ - * | add, subtract, multiply | 7 * 3 gives 21 |
/ | divide (two ints drop the decimal part) | 7 / 2 gives 3, but 7.0 / 2 gives 3.5 |
% | remainder after dividing | 7 % 2 gives 1; 17 % 5 gives 2 |
++ -- | add 1 / subtract 1 (a short way to write count = count + 1) | if count is 2, count++; makes it 3 |
+ with text | joins text and a value into one piece of text | "Score: " + 92 gives Score: 92 |
3Conditions let a program choose a path
if (score >= 75) {
passed = true;
} else {
passed = false;
} if/else as a flowchart. With a score of 92, only the YES path runs.If the score is 75 or higher, one path runs; otherwise, the other. Comparisons use == (equal), != (not equal), <, >, <=, >=. Each comparison gives true or false.
Good to know: to compare two Strings, use name.equals("Ana"), not ==. With text, == can say false even when the letters match, because it checks whether both are the very same thing in memory. (You will meet this idea, "the same object", in the Linked lists lesson.)
More than two paths: else if. When there are several cases, chain the checks. Java checks from the top and runs only the first part whose check is true; the rest are skipped:
int score = 82;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 75) {
System.out.println("Passed"); // this one runs
} else {
System.out.println("Failed");
} Two checks at once: &&, ||, !. Sometimes one check is not enough. To enter the exam room, you need your ID and your permit. To pay at the canteen, cash or GCash will do. Java has three words for this:
| Operator | Read it as | True when… |
|---|---|---|
a && b | "a and b" | both are true |
a || b | "a or b" | at least one is true |
!a | "not a" | a is false |
boolean hasID = true;
boolean hasPermit = false;
System.out.println(hasID && hasPermit); // false: both are needed
System.out.println(hasID || hasPermit); // true: one is enough
System.out.println(!hasPermit); // true: "not false" You will see these in later lessons, for example while (!queue.isEmpty()): "while the queue is not empty."
4Loops repeat a block of work
for (int i = 0; i < 4; i++) {
System.out.println(i); // prints 0, 1, 2, 3
} A loop runs the same lines again and again, with a new value of i each round. A for loop has three controls: where to start (i = 0), when to keep going (i < 4), and how to update after each round (i++).
The while loop. A for loop is best when you know how many rounds you need. A while loop keeps going as long as a check is true, like playing an arcade game while you still have coins:
int coins = 3;
while (coins > 0) { // check first
System.out.println("Play one round");
coins--; // use one coin
}
System.out.println("No coins left"); It prints "Play one round" 3 times, then "No coins left". The check comes before every round, so if coins started at 0, the block would not run at all.
Something inside must change
The block must change what the check looks at (here, coins--;). Without that line, coins stays 3, coins > 0 is true forever, and the loop never ends. You will see this same bug in the Linked lists lesson.
5A method performs one reusable task
static int larger(int a, int b) {
if (a > b) return a;
return b;
} Method
A named block of code that does one task. Its parameters are the inputs it receives; its return value is the output it gives back.
Think of a method as a small machine: larger(3, 8) puts 3 into a and 8 into b, and the machine gives back 8.
Notice that if (a > b) return a; has no braces. When an if controls only one line, Java lets you leave the braces out. And return ends the method right away, so return b; runs only when a > b is false. That is why no else is needed.
Two more words in the first line. int before the name is the type of the value the method gives back. A method that gives nothing back (it only prints, for example) says void there instead, like static void greet(String name). And static lets main (block 8) call the method directly. You will learn about methods that are not static in the Linked lists lesson.
Methods matter in this course because every operation on a data structure is a method, such as push(), pop(), and insert(), and we can test each one on its own.
6An array is a row of numbered slots
Array and index
An array is a fixed number of slots, side by side, that all hold the same type of value. Each slot's numbered position is its index.
Counting starts at 0, so arr[2] is the third slot: 42. The array is the first data structure of this course: you will see it again in Introduction to DSA, and it gets a whole lesson in Arrays.
Making an array in Java. There are two ways: list the values, or ask for empty slots and fill them later.
int[] arr = {19, 3, 42, 7, 56}; // 5 slots with values
int[] scores = new int[5]; // 5 empty slots (all 0)
scores[0] = 92; // store 92 in slot 0
System.out.println(arr[2]); // 42
System.out.println(scores.length); // 5 new int[5] makes 5 empty slots that start at 0.Here is how to read each line aloud:
| Code | Read it as |
|---|---|
int[] arr = {19, 3, 42, 7, 56}; | "make an int array named arr holding these 5 values." int[] means "an array of ints." |
int[] scores = new int[5]; | "make an int array with 5 slots." Each slot starts at 0. |
scores[0] = 92; | "store 92 in slot 0." |
scores.length | "how many slots": 5. The last index is length - 1, which is 4. |
7Trace code one line at a time
1int total = 0;
2for (int i = 1; i <= 3; i++) {
3 total = total + i;
4}
5System.out.println(total); | Round | i | total |
|---|---|---|
| before | – | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
total after each round. The trace table above lists the same values.A trace table shows how each variable changes, step by step. Output: 6. You will use trace tables in every lesson of this course.
8Putting it together: a complete program
So far you have seen pieces of code. To actually run them, Java needs them inside a complete program. Think of a school building: the building has a name, it has rooms, and everyone comes in through the front door.
main is the front door: Java always starts there.Here is a complete program that uses the larger method from block 5:
1public class Main {
2 static int larger(int a, int b) {
3 if (a > b) return a;
4 return b;
5 }
6
7 public static void main(String[] args) {
8 int big = larger(4, 9);
9 System.out.print("Larger: ");
10 System.out.println(big);
11 System.out.println("Done!");
12 }
13} ▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.
larger is written first, but Java starts at main.Here is how to read the new lines:
| Code | Read it as |
|---|---|
public class Main { … } | "a class named Main." All the code goes inside its braces. The file must be saved as Main.java: same name as the class. |
static int larger(int a, int b) | "a method inside the class" (block 5). It runs only when something calls it. |
public static void main(String[] args) | "the starting point." Java runs main first, one line at a time, from top to bottom. Copy this line exactly as it is; you do not need to understand args for this course. |
System.out.print(…) | "show this, and stay on the same line." |
System.out.println(…) | "show this, then move to a new line." (ln stands for "line".) |
That is why the output has Larger: and 9 on the same line: print did not move to a new line, and the next println continued there.
OutputLarger: 9
Done!
Good to know: in later lessons, some files hold a second class, like class Node, written outside the braces of Main. Only the class that holds main is public, and the file is named after it.
Part 2 · When code fails
Three main kinds of errors
Java errors are usually sorted into three main kinds, by when they show up: before the program runs, while it runs, or at the end, as a wrong answer. Knowing which one you have tells you where to look:
| Type | What happens | Example |
|---|---|---|
| Compile-time error (often a syntax error) | Java's compiler rejects the code, so it never runs. Most of these break Java's grammar (syntax). | a missing ;, or int x = "Ana"; (text in an int) |
| Runtime error | The program starts, then crashes partway. Java calls these exceptions: errors Java reports while the program is running. If nothing handles one, the program stops. | arr[5] when arr has 5 slots (indexes 0 to 4) |
| Logic error | The program runs to the end, but the answer is wrong. No error message warns you. | writing score > 75 when the rule is 75 or higher (>=) |
Good to know: are there only three?
These three are the main kinds in most Java books, such as Think Java. Some books list more. Semantic errors are code that follows the grammar but makes no sense, like putting text in an int; in Java, the compiler catches these, so they count as compile-time errors here. Linker errors happen in languages like C and C++, not in everyday Java.
A simple debugging habit
Read the exact error message. Trace a small example by hand. Change one thing, then test again.
Part 3 · Check yourself
Self-check
Not graded. Tap an answer to see if you got it, and read why.
-
After
int x = 5;and thenx = x + 2;, what is inx?The
=sign stores, it does not compare. Java first works out the right side (5 + 2 = 7), then stores 7 inx. -
What does
17 % 5give in Java?%gives the remainder: 17 ÷ 5 = 3 remainder 2. -
What does this print?
for (int i = 0; i < 3; i++) System.out.println(i);Start at 0; keep going while
i < 3. Soiis 0, 1, 2. At 3 the condition is false and the loop stops. -
What does
larger(4, 9)return?4 goes into
aand 9 intob.a > bis false, so the method returnsb: 9. -
Which array index holds the third value?
Counting starts at 0: index 0 is the first value, index 1 the second, index 2 the third.
-
What does this print?
int n = 3; while (n > 0) { System.out.print(n + " "); n--; }The check comes first. n is 3, 2, 1: each round prints n, then
n--makes it 1 smaller. When n is 0,n > 0is false and the loop ends, so 0 is never printed. -
What is
(5 > 3) && (2 > 4)?&&needs both sides true. 5 > 3 is true, but 2 > 4 is false, so the answer is false. (With||, one true side is enough, so it would be true.) -
With
score = 82, the code checksscore >= 90, thenelse if (score >= 75), thenelse. Which part runs?Java checks from the top and stops at the first true check. 82 >= 90 is false; 82 >= 75 is true, so only "Passed" runs.
-
A file holds a class with two methods,
larger(written first) andmain. Where does Java start running?Java always starts at
main, wherever it sits in the file. Other methods run only when something calls them. -
The program runs, but the answer is wrong. What kind of error is this?
A logic error: the code follows Java's rules and does not crash, but the steps are wrong (for example, a wrong condition).
-
You forgot a
;and the code will not compile. What kind of error is this?A missing
;breaks Java's grammar, so the compiler rejects the code and the program never starts: a compile-time (syntax) error.
Score: 0 / 11
Key takeaways
=stores: work out the right side, then store it in the variable on the left.- Conditions choose a path (
else iffor more cases;&&= both,||= at least one,!= not). Loops repeat:forfor a known number of rounds,whileas long as a check is true. Methods package one task with inputs and an output. - Array indexes start at 0, so
arr[2]is the third value.new int[5]makes 5 slots, andlengthcounts them. - A complete program is a class with a
mainmethod. Java always starts atmain. - A trace table shows how each variable changes, one step at a time.
- Compile-time (syntax) errors stop the program before it runs, runtime errors crash it partway, and logic errors give wrong answers.
Next lesson: Introduction to DSA.
References
- A. B. Downey and C. Mayfield, Think Java, 2nd ed. O'Reilly, 2019 (compile-time, run-time, and logic errors).
- Oracle, "The Java Tutorials: Language Basics." docs.oracle.com