ma'am audrey's lessons

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:

  1. read a line like int score = 92; aloud, and explain what = does;
  2. predict what short code with conditions (if, else if, &&, ||, !), loops (for, while), and methods prints;
  3. make an array in Java and find a value in it by its index (counting from 0);
  4. trace a loop with a trace table;
  5. read a complete Java program: where it starts (main) and what it prints;
  6. 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;
name"Ana"Stringscore92intaverage85.0doublepassedtruebooleanname tag on top · value inside · type below
Each variable is a box with a name tag. The type decides what can go inside.

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 + 2Step 1: work out the right sidex + 25 + 27x is 5 right nowStep 2: store it in xx57Before: x holds 5.After: x holds 7.The old 5 is replaced.store
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:

OperatorMeaningExample
+ - *add, subtract, multiply7 * 3 gives 21
/divide (two ints drop the decimal part)7 / 2 gives 3, but 7.0 / 2 gives 3.5
%remainder after dividing7 % 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 textjoins 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;
}
score is 92score >= 75 ?YESNOpassed = true;passed = false;Only one path runs. 92 >= 75 is true, so YES.
The same 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");
}
score is 82score >= 90 ?YESExcellentNOscore >= 75 ?YESPassedNOelse: Failedskipped(gray)82 >= 90? No. 82 >= 75? Yes: print Passed.Java stops at the first true check.
The same code as a ladder. With 82, the first check is false, the second is true, so only "Passed" runs.

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:

&& (and): BOTH must be trueEnter the exam room? hasID && hasPermitID ✓&&permit ✓trueID ✓&&permit ✗false|| (or): at least ONE is trueCan you pay? hasCash || hasGCashcash ✗||GCash ✓truecash ✗||GCash ✗false! (not): flips true and false!truefalseRead ! as "not": !hasPermit is "has no permit".
And needs both; or needs at least one; not flips the answer.
OperatorRead it asTrue 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
}
Round 1i = 00 < 4 ✓prints 0i++Round 2i = 11 < 4 ✓prints 1i++Round 3i = 22 < 4 ✓prints 2i++Round 4i = 33 < 4 ✓prints 3i = 4: 4 < 4 is falsethe loop stopsSame lines every round; only i changes.
The loop round by round. It stops the first time the condition is false.

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");
coins = 3coins > 0 ?YESplay one roundcoins--;checkagainNONo coinsleftcoins:3round 12round 21round 30stopEach round uses one coin. At 0 the check isfalse, so the loop ends.
Check, run the block, check again. The loop ends the first time the check is false.

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.

larger(3, 8)a = 3b = 8largerkeeps the bigger one8Inputs(parameters)Output(return)
Inputs go in as parameters; the return value comes out.

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

1903142273564

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.

arr[2] opens locker 20191324237456Number plate = index (starts at 0).Locker 2 is the third locker. Inside: 42.
An array is like a row of numbered lockers. The index is the number plate.

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
int[] arr = {19, 3, 42, 7, 56};1903142273564Values in braces: Java counts them (5 slots).int[] scores = new int[5];0001020304new int[5]: 5 empty slots. Each starts at 0.scores[0] = 92;92001020304Store 92 in slot 0. The others stay 0.scores.length is 5 (indexes 0 to 4)
Listing the values fills the slots. new int[5] makes 5 empty slots that start at 0.

Here is how to read each line aloud:

CodeRead 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);
Rounditotal
before–0
111
223
336
What happens to totalstart0+1i = 11+2i = 23+3i = 36prints 6A trace table writes down each of these boxes as a row.
The value of 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.

A program is like a school buildingclass Mainlargera room forone jobmainthe front doorJava enters here firstOther rooms are usedonly when main calls them.
The class is the building. Each method is a room for one job. 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.

Inside the file Main.javapublic class Main {the classstatic int larger(int a, int b) {if (a > b) return a;return b;}a methodpublic static void main(String[] args) {int big = larger(4, 9);System.out.print("Larger: ");System.out.println(big);System.out.println("Done!");}main: the start}1234OutputLarger: 9Done!1Java starts at main, not at the top of the file.2main calls larger(4, 9).3larger gives back 9; main stores it in big.4The prints run in order, top to bottom.
The same file, with the run order numbered. larger is written first, but Java starts at main.

Here is how to read the new lines:

CodeRead 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:

TypeWhat happensExample
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 errorThe 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 errorThe 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.

  1. After int x = 5; and then x = x + 2;, what is in x?

  2. What does 17 % 5 give in Java?

  3. What does this print? for (int i = 0; i < 3; i++) System.out.println(i);

  4. What does larger(4, 9) return?

  5. Which array index holds the third value?

  6. What does this print? int n = 3; while (n > 0) { System.out.print(n + " "); n--; }

  7. What is (5 > 3) && (2 > 4)?

  8. With score = 82, the code checks score >= 90, then else if (score >= 75), then else. Which part runs?

  9. A file holds a class with two methods, larger (written first) and main. Where does Java start running?

  10. The program runs, but the answer is wrong. What kind of error is this?

  11. You forgot a ; and the code will not compile. What kind of error is this?

Score: 0 / 11

Key takeaways

  1. = stores: work out the right side, then store it in the variable on the left.
  2. Conditions choose a path (else if for more cases; && = both, || = at least one, ! = not). Loops repeat: for for a known number of rounds, while as long as a check is true. Methods package one task with inputs and an output.
  3. Array indexes start at 0, so arr[2] is the third value. new int[5] makes 5 slots, and length counts them.
  4. A complete program is a class with a main method. Java always starts at main.
  5. A trace table shows how each variable changes, one step at a time.
  6. 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

  1. A. B. Downey and C. Mayfield, Think Java, 2nd ed. O'Reilly, 2019 (compile-time, run-time, and logic errors).
  2. Oracle, "The Java Tutorials: Language Basics." docs.oracle.com