Prerequisites for Object-Oriented Programming with Java
The course starts from how a computer works and soon moves on to writing, compiling, and running Java programs. The 28 topics on this page gather what the course builds on in six groups: computer fundamentals, number systems, algorithms and flowcharts, basic programming concepts, the tools needed to write Java, and two habits of thought behind objects.
Each card has a short explanation, a small example, links to the slides where the topic is used, and a check question; click the question to open its answer.
Computer fundamentals
What happens inside the machine while a program is stored, loaded into memory, and run.
Hardware: processor, memory, and storage
A program sits on the disk as a file. To run, it is loaded into main memory (RAM); the processor then executes the program's instructions one by one, reading and writing data in memory. RAM is fast but loses its contents when the power is cut, while the disk keeps storing files.
Why it mattersWhile a Java program runs, its variables, objects, and references live in memory; after the program ends, only what was written to a file remains.
Check question
A program executes int score = 90; and then the computer is shut down. Is the value 90 still there the next day?
No. The variable exists in RAM only while the program is running. To keep the value, it has to be written to a file or a database.
Runtime rt = Runtime.getRuntime();
System.out.println(rt.availableProcessors()); // for example 8 cores
System.out.println(rt.maxMemory() / (1024 * 1024) + " MB"); // memory the JVM may useFiles, folders, and paths
A path names a file: an absolute path starts at the root (C:\Users\ann\course\Hello.java), while a relative path starts at the current working directory (course\Hello.java). The extension tells the type of file: .java is source code, .class is compiled bytecode. Windows hides known extensions by default, so a file can end up named Hello.java.txt without anyone noticing.
Why it mattersjavac and java are run in the folder that holds the source file; file input and output also open files with relative or absolute paths.
Check question
The working directory is C:\course and a program opens a file with new File("grades.txt"). Which file is it?
C:\course\grades.txt. A relative path is resolved against the directory the program was started in.
C:\Users\ann\course\Hello.java absolute path (Windows)
/home/ann/course/Hello.java absolute path (Linux, macOS)
course\Hello.java relative path from the C:\Users\ann directory
Hello.java source code
Hello.class bytecode produced by javacPrograms, compilers, and interpreters
A processor executes only machine code. A compiler translates the whole program in advance; an interpreter reads and executes the program step by step. Java combines the two: javac compiles source code into platform-independent bytecode, and the Java Virtual Machine (JVM) interprets this bytecode and, while the program runs, compiles the frequently used parts into machine code.
Why it mattersThe difference between a compile-time error and a run-time error, and the roles of the javac and java commands, come from this two-step process.
Check question
A Hello.class file was produced on Windows. Can this file be run on Linux?
Yes. Bytecode is not the machine code of any particular processor; every operating system that has a JVM can run it with the command java Hello.
Hello.java --javac--> Hello.class --java (JVM)--> program output
(source code) (bytecode)Number systems and data representation
How numbers and characters are stored as bits, and the surprising results this has.
Binary, decimal, and hexadecimal systems
In base 2 each digit is worth a power of two: 1101₂ = 8 + 4 + 0 + 1 = 13. Hexadecimal packs four bits into a single digit from 0–9 and A–F, so 1111 1111₂ = FF₁₆ = 255. You should be able to convert a number to binary by repeatedly dividing by 2 and convert back by adding up place values.
Why it mattersBit patterns, two's complement representation, color values, and character codes are written in these bases; Java also accepts binary and hexadecimal literals.
Check question
What are 1011₂ and 2A₁₆ in decimal?
1011₂ = 8 + 2 + 1 = 11 and 2A₁₆ = 2·16 + 10 = 42.
System.out.println(Integer.toBinaryString(13)); // 1101
System.out.println(Integer.toHexString(255)); // ff
System.out.println(0b1101 + " " + 0x1F); // 13 31
System.out.println(Integer.parseInt("101", 2)); // 5Bits, bytes, and integer ranges
n bits can hold 2ⁿ different values. Java stores signed integers in two's complement form, so a byte (8 bits) takes values from −128 to 127, and an int (32 bits) takes values from about −2.1 billion to 2.1 billion. When a result does not fit the type, no error occurs; the value silently wraps around.
Why it mattersChoosing between int and long, and noticing overflow in factorials, sums, and products, depend on knowing these limits.
Check question
How many different values can be stored in 8 bits, and what is the range of Java's byte type?
2⁸ = 256 values; byte uses them for −128 … 127.
byte b = (byte) 130;
System.out.println(b); // -126
int max = Integer.MAX_VALUE; // 2147483647
System.out.println(max + 1); // -2147483648 (overflow)
System.out.println((long) max + 1); // 2147483648Fractional numbers are approximate
A double stores a binary fraction, so most decimal fractions such as 0.1 can be held only approximately, and small errors appear in sums. For this reason two double values are compared not with == but with a tolerance. The quotient of two integers is also an integer: the result of 7 / 2 is 3, while the result of 7 / 2.0 is 3.5.
Why it mattersIf these two effects are not taken into account, averages, unit conversions, and money calculations silently give wrong results.
Check question
Why are money amounts often stored as whole numbers of cents?
Integers are exact, whereas values such as 0.10 cannot be represented exactly as a double, and rounding errors accumulate as many such values are added.
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1 + 0.2 == 0.3); // false
System.out.println(Math.abs(0.1 + 0.2 - 0.3) < 1e-9); // true
System.out.println(7 / 2 + " " + 7 / 2.0); // 3 3.5Characters: ASCII and Unicode
Every character is stored as a number: in ASCII, 'A' is 65, 'a' is 97, and '0' is 48. Unicode extends this numbering to all writing systems; letters of other alphabets have codes too (for example, é is 233). Java's char holds a 16-bit Unicode unit and can be used in arithmetic. Files usually store text in the UTF-8 encoding.
Why it mattersCharacter arithmetic such as converting the character '7' to the number 7, comparing strings, and reading non-English text from a file correctly all rest on character codes.
Check question
The code of the character 'a' is 97. What does System.out.println('a' + 1); print?
98. A char + int operation is computed as an int; (char) ('a' + 1) prints b.
char c = 'A';
System.out.println((int) c); // 65
System.out.println((char) (c + 2)); // C
System.out.println('7' - '0'); // 7
System.out.println((int) 'é'); // 233Algorithms and flowcharts
Planning the solution before writing code, and tracing code by hand.
Algorithm: input, processing, output
An algorithm is a sequence of a finite number of precise steps that transforms the given input into the desired output and always halts. Before coding, the problem is defined clearly: what is given, what must be produced, and which special cases exist (zero, negative numbers, an empty list).
Why it mattersEvery exercise and example program in the course starts from an algorithm; most mistakes come not from Java syntax but from a vague problem definition.
Check question
“Keep adding 1 to x until x is negative.” If x starts at 5, is this an algorithm?
Not in the strict sense: since x only grows, on paper the process never stops. (In Java an int eventually overflows; that is a bug, not a plan.) An algorithm has to terminate.
Read a, b
If a > b then
max ← a
Otherwise
max ← b
Write maxFrom pseudocode to code
Pseudocode describes the steps of an algorithm in plain, orderly language without worrying about syntax. Then a Java counterpart is written for each line: Read becomes reading with Scanner, ← becomes an assignment, Loop becomes a loop, and Write becomes a System.out.println call.
Why it mattersWriting the steps first separates thinking about the solution from fighting compiler errors.
Check question
What is printed in the example for n = 4?
10, because 1 + 2 + 3 + 4 = 10.
sum ← 0 int sum = 0;
Loop i = 1 to n for (int i = 1; i <= n; i++) {
sum ← sum + i sum = sum + i;
}
Write sum System.out.println(sum);Flowcharts and the three control structures
A flowchart draws an algorithm with standard shapes: an oval for start and end, a parallelogram for input and output, a rectangle for computation, and a diamond for a decision. Every algorithm can be built from three structures: sequence, selection (if), and repetition (loop).
Why it mattersWhen the flow of a loop or of nested decisions is drawn, it is easier to see where the condition is tested and when the program leaves the loop.
Check question
In which flowchart shape is a condition such as n > 0 written, and how many exits does that shape have?
It is written in the diamond (decision); it has two exits: one for true (yes) and one for false (no).
( start / end ) oval program starts / ends
/ input, output / parallelogram Scanner, System.out.println
[ computation ] rectangle sum = sum + i;
< condition? > diamond if (n > 0), while (i <= n)Tracing code by hand
Tracing means running a program on paper: a table records the value of every variable after each step. It is the most reliable way to predict the output of a loop, to find an off-by-one error, and to understand someone else's code.
Why it mattersMany slides and exam questions ask for the output of a short piece of code; a trace table lets you answer these without a computer.
Check question
int x = 5; while (x > 1) x = x / 2; How many times does the loop body run, and what is x at the end?
Twice: x becomes 5 → 2 → 1 in turn, and then the condition x > 1 is false. At the end x is 1 (integer division).
int s = 0;
for (int i = 1; i <= 4; i++) s += i;
// i : 1 2 3 4
// s : 1 3 6 10 -> the loop ends when i becomes 5Logarithms and growth rates
log₂ n tells to which power 2 must be raised to get n: since 2¹⁰ = 1024, log₂ 1024 = 10. Halving a number again and again brings it down to 1 in about log₂ n steps; that is why the logarithm grows very slowly: when n grows a thousandfold, log₂ n grows by only about 10. As the input size n grows, different functions grow at very different rates; from small to large the order is 1, log n, n, n log n, n², 2ⁿ. With n² growth, doubling n quadruples the work; with 2ⁿ growth, even increasing n by 1 doubles the work.
Why it mattersThe costs of searching and sorting algorithms and of array and collection operations are compared using notations such as O(1), O(log n), O(n), O(n log n), and O(n²). The exponentially growing number of calls in plain recursive Fibonacci is explained by the same idea.
Check question
In a sorted array the search space is halved at each step. If the array has 1,000,000 elements, what is the maximum number of steps needed?
About 20. Since 2²⁰ = 1,048,576, log₂ 1,000,000 ≈ 19.9; binary search makes at most ⌊log₂ n⌋ + 1 = 20 comparisons. Linear search, which looks at the elements one by one, can take up to 1,000,000 comparisons.
int n = 1000, steps = 0;
while (n > 1) {
n = n / 2; // halved on every round
steps++;
}
System.out.println(steps); // 9 (log₂ 1000 ≈ 9.97)
// n log₂ n n log₂ n n²
// 10 ≈ 3.3 ≈ 33 100
// 1000 ≈ 10 ≈ 10,000 1,000,000Factorial, summation notation, and inductive definitions
n! (n factorial) is the product of the numbers from 1 to n, and 0! = 1 by convention: 5! = 120. The symbol Σ writes a sum compactly: the sum of i from 1 to n is n(n + 1)/2. A sequence can also be defined inductively: one or several starting values are given, and each term is found from the earlier ones by a rule. n! = n · (n − 1)! and F(n) = F(n − 1) + F(n − 2) are such definitions. The number of ways to choose k items out of n is the combination C(n, k) = n! / (k! (n − k)!); in Pascal's triangle each number is the sum of the two numbers above it: C(n, k) = C(n − 1, k − 1) + C(n − 1, k).
Why it mattersA recursive method turns such a definition directly into code: the starting value becomes the base case and the rule becomes the recursive step. The factorial, Fibonacci, Catalan, and Bell sequences and Pascal's triangle are given with this notation.
Check question
What is the term a(4) of the sequence defined by a(0) = 3 and the rule a(n) = a(n − 1) + 2?
11. The terms are 3, 5, 7, 9, 11 in turn; at each step 2 is added to the previous term.
static long factorial(int n) {
if (n == 0) return 1; // base: 0! = 1
return n * factorial(n - 1); // rule: n! = n · (n − 1)!
}
static long combination(int n, int k) {
if (k == 0 || k == n) return 1; // the edges of the triangle
return combination(n - 1, k - 1) + combination(n - 1, k);
}
// factorial(5) == 120, combination(5, 2) == 10Programming concepts
The basic building blocks of every program, whatever the language.
Variables, types, and assignment
A variable is a named place in memory whose type determines which values it can hold. Java checks types at compile time: an int cannot hold "5", and a variable must be given a value before it is read. The = sign is not mathematical equality but assignment (the value on the right side is copied into the variable).
Why it mattersEvery program keeps its data in variables; primitive types and reference types later behave differently when they are assigned or passed to methods.
Check question
int a = 3; int b = a; a = 10; What is b?
3. The assignment b = a copied the value at that moment; changing a later does not affect b.
int age = 20;
double gpa = 3.25;
boolean passed = gpa >= 2.0;
String name = "Ann";
age = age + 1;
System.out.println(name + " " + age + " " + passed); // Ann 21 trueExpressions and operators
Arithmetic follows precedence rules: * / % are performed before + −, and operators of equal precedence are applied from left to right. The remainder operator % together with integer division / splits a number into its digits. When one of the operands of + is a String, + does not add but concatenates the texts.
Why it mattersDigit sums, odd/even tests, divisibility, and formatted output rest on these operators.
Check question
For n = 4729, what are n % 10 and n / 10?
9 (the last digit) and 472 (the number with its last digit removed).
System.out.println(17 / 5); // 3
System.out.println(17 % 5); // 2
System.out.println(2 + 3 * 4); // 14
System.out.println("1" + 2 + 3); // 123
System.out.println(1 + 2 + "3"); // 33Logical expressions
Conditions are combined with && (and), || (or), and ! (not). Java evaluates them from left to right and stops as soon as the result is known (short-circuit evaluation); so a later part can rely on an earlier check. De Morgan's laws distribute a negation inward: !(a && b) is the same as !a || !b.
Why it mattersRange checks, input validation, and loop conditions are boolean expressions; a misplaced && or || is among the most common logic errors.
Check question
How is !(x >= 1 && x <= 10) written without using !?
x < 1 || x > 10 (De Morgan's law).
int x = 7;
boolean inRange = x >= 1 && x <= 10; // true
boolean outside = !(x >= 1 && x <= 10); // false: same as x < 1 || x > 10
int d = 0;
if (d != 0 && 10 / d > 1) // the right side is skipped: no division by zero
System.out.println("big");
System.out.println(inRange + " " + outside); // true falseDecisions: if, else if, switch
if runs a block if its condition is true; else provides the alternative. An else-if chain tests the conditions in order and runs only the first branch whose condition holds. switch picks a case according to the value of a single expression.
Why it mattersGrade calculation, menus, input checks, and almost every algorithm in the course make decisions.
Check question
int x = 5; if (x > 3) print "A"; else if (x > 1) print "B"; What is printed?
Only A. The first true condition wins and the rest of the chain is skipped; B is not printed even though x > 1 is also true.
int score = 72;
if (score >= 85) System.out.println("A");
else if (score >= 70) System.out.println("B"); // B
else System.out.println("C");Loops: for, while, do-while
A loop repeats a block as long as its condition is true. for suits cases where the number of repetitions is known, while suits a condition tested before every round, and do-while suits cases where the body must run at least once. Every loop needs a variable that changes in such a way that the condition eventually becomes false.
Why it mattersSums, searches, patterns, input loops, and array operations are written with loops; infinite loops and loops that run one time too few or too many are frequent mistakes.
Check question
How many times does the loop for (int i = 10; i > 0; i -= 3) run?
Four times: for i = 10, 7, 4, and 1; then i becomes −2.
for (int i = 0; i < 3; i++) System.out.print(i + " "); // 0 1 2
System.out.println();
int n = 1234, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
System.out.println(digits); // 4Functions: parameters and return values
A function (a method in Java) gathers a computation under one name: it receives values through parameters and can return a single result with return; a void method returns no value. Java passes arguments by value; so a method cannot change the caller's int variable.
Why it mattersPrograms are divided into methods from the very beginning; classes, too, are structures that bring methods and data together.
Check question
After the definition static void inc(int x) { x++; } , if int a = 5; inc(a); is run, what is a?
Still 5. The method received a copy of the value; it changed only its own parameter x.
static int square(int x) { return x * x; }
static void greet(String name) { System.out.println("Hello " + name); }
// inside main:
int r = square(5) + square(2); // 29
greet("Ann"); // Hello AnnArrays and strings: a first look
An array holds a fixed number of values of a single type; the values are numbered with indices from 0 to length − 1. A String is a sequence of characters whose positions are also numbered from 0. If the program tries to read outside these bounds, it stops with an exception.
Why it mattersGrade lists, matrices, text processing, and the collection classes all rest on access by index.
Check question
int[] a = {4, 8, 15}; What happens if a[3] is read?
An ArrayIndexOutOfBoundsException is thrown; the valid indices are 0, 1, and 2.
int[] a = {4, 8, 15};
System.out.println(a.length + " " + a[0] + " " + a[a.length - 1]); // 3 4 15
String s = "Java";
System.out.println(s.length() + " " + s.charAt(1)); // 4 aTools and setup
Installing Java, compiling and running programs, and reading what the tools report.
Command-line basics
On the command line (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux), programs are run by typing their names. The prompt shows the current working directory; cd changes this directory, dir (ls on macOS/Linux) lists files, and mkdir creates a folder. The Tab key completes file names, and the up-arrow key brings back earlier commands.
Why it mattersjavac and java are command-line programs; running them by hand shows what an IDE's Run button does behind the scenes.
Check question
The prompt looks like C:\Users\ann\course>. What is the working directory after the command cd .. ?
The parent folder, C:\Users\ann.
C:\Users\ann> mkdir course creates a folder
C:\Users\ann> cd course enters the folder
C:\Users\ann\course> dir lists the files (ls on macOS/Linux)
C:\Users\ann\course> cd .. goes up one level
C:\Users\ann>Installing the JDK
The Java Development Kit (JDK) contains the javac compiler, the java launcher together with the JVM, and the standard library. A long-term support (LTS) release such as JDK 17 or 21 (for example from Adoptium or Oracle) is a good choice. For the commands to work from any directory, the JDK's bin folder must be added to the PATH; the installer or the user does this. The commands java -version and javac -version verify the installation.
Why it mattersWithout a working JDK, neither the command-line examples nor an IDE can compile Java code.
Check question
The command line answers 'javac' is not recognized as an internal or external command. What is a likely cause?
The JDK's bin folder is not on the PATH, or only a runtime without a compiler is installed.
> java -version
openjdk version "21.0.3" 2024-04-16 LTS
OpenJDK Runtime Environment Temurin-21.0.3+9 (build 21.0.3+9-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.3+9 (build 21.0.3+9-LTS, mixed mode, sharing)
> javac -version
javac 21.0.3javac and java: compiling and running
The command javac Hello.java compiles the source file and, if there are no errors, writes Hello.class. The command java Hello then starts the JVM and runs this class's main method (the name is given without the .class extension). A public class must be saved in a file with exactly the same name, including upper and lower case.
Why it mattersEvery program in the course has this form: a class with a main method is first compiled and then run.
Check question
A file named Test.java contains the definition public class Hello. What does javac Test.java report?
A compile error: class Hello is public, should be declared in a file named Hello.java.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
> javac Hello.java (Hello.class is created)
> java Hello
Hello, Java!Working with an IDE
An integrated development environment (IDE) brings together an editor, a compiler, and a debugger: it underlines errors as you type, completes names, and compiles and runs the program with the Run button. Common choices are IntelliJ IDEA, Eclipse, and Visual Studio Code with Java extensions. The debugger stops at a breakpoint and executes the program line by line while showing the variables.
Why it mattersLarge programs made of several classes are written in an IDE; with long code, the debugger replaces tracing by hand.
Check question
The debugger has stopped at the line int r = square(5); What is the difference between Step Over and Step Into?
Step Over runs the whole call and stops at the next line of the current method; Step Into enters the square method and stops at its first line.
IntelliJ IDEA psvm + Tab -> public static void main(String[] args)
IntelliJ IDEA sout + Tab -> System.out.println();
Eclipse main + Ctrl+Space, sysout + Ctrl+Space
in all IDEs clicking the margin next to a line sets a breakpointReading error messages
javac reports a compile-time error with the file name, the line number, and a caret (^) placed under the problem; in this case no .class file is produced. A run-time error is an exception: the program compiles but stops while running and prints the type of the exception, a message, and the stack trace of method calls. You usually start with the first message and its line number.
Why it mattersFixing errors quickly depends on reading these messages instead of guessing.
Check question
Is int x = "5"; a compile-time error or a run-time error?
It is a compile-time error (incompatible types: String cannot be converted to int); javac rejects this line before the program runs.
Hello.java:3: error: ';' expected
System.out.println("Hello")
^
1 error
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Divide.main(Divide.java:4)Reading API documentation
The Java standard library is documented in Javadoc pages (docs.oracle.com) organized by package and class. A method's header says what it needs and what it returns: in the header public static int parseInt(String s), the parameter is a String and the result is an int; static shows that the method is called through the class, as in Integer.parseInt("42").
Why it mattersClasses such as String, Math, Scanner, ArrayList, and HashMap are used through their documented methods.
Check question
Math.max has separate versions for int and double. What does Math.max(3, 7.5) return?
7.5 as a double: since one of the arguments is a double, the double version is chosen and the value 3 is widened to 3.0.
public static int parseInt(String s) // in the Integer class
public int length() // in the String class
public static double sqrt(double a) // in the Math class
int n = Integer.parseInt("42") + 1; // 43
int k = "Java".length(); // 4
double r = Math.sqrt(16); // 4.0Getting ready for objects
Two habits of thought that object-oriented programming rests on.
Classification: is-a and has-a
Everyday objects are divided into categories (every dog is an animal) and are made of parts (every car has an engine). Object-oriented programming models the first relationship with inheritance (is-a) and the second with fields that refer to other objects (has-a). Telling these two relationships apart in a sentence is the first step of class design.
Why it mattersChoosing between extends and a field, and building class hierarchies, starts from this distinction.
Check question
A student has a student number; a student is a person. Which is the is-a and which is the has-a relationship?
Student is-a Person (inheritance); Student has-a student number (a field).
class Animal { }
class Dog extends Animal { } // every Dog is an Animal
class Engine { }
class Car {
Engine engine = new Engine(); // every Car has an Engine
}Abstraction and decomposition
Decomposition divides a big problem into small parts that can be solved separately; abstraction keeps only the important aspects of a part and hides how it works inside. Using the Math.sqrt method without knowing its algorithm is abstraction; writing a program as several small methods is decomposition.
Why it mattersMethods, classes, interfaces, and encapsulation are the tools of these two ideas.
Check question
A program reads grades, computes their average, and prints a report. Into which parts can this program be divided?
For example, into three methods: one that reads the grades, one that computes the average, and one that prints the report. Each can be written and tested separately.
static int[] readGrades() { ... }
static double average(int[] g) { ... }
static void printReport(double avg) { ... }
// main only puts the parts together:
printReport(average(readGrades()));No topic matches the search and filter.
The outputs in the Java examples were checked by compiling the programs with javac --release 8 and running them; outputs marked “for example” vary from computer to computer.