Home
← All UnitsUnit 1: Primitive Types & Intro to Java
Unit 1

Primitive Types & Intro to Java

Before writing code, you need to understand the machine running it and the language you're writing in. This unit covers the foundations.

Computer Hardware

Hardware is the physical stuff you can touch. Every computer — from a phone to a server rack — has these core components working together.

CPU (Central Processing Unit)

The "brain" of the computer. It executes instructions from programs by performing arithmetic, logic, and control operations. Modern CPUs have multiple cores, allowing them to run instructions in parallel.

Motherboard

The main circuit board that connects all components together. The CPU, RAM, storage, and peripherals all plug into the motherboard. Think of it as the nervous system connecting every organ.

Busses

Electrical pathways that carry data between components. The data bus moves data, the address bus tells where to send it, and the control bus coordinates the operation. Wider busses = more data moved per cycle.

Hard Drive (Storage)

Long-term, non-volatile storage — data persists when power is off. HDDs use spinning magnetic platters; SSDs use flash memory chips (faster, no moving parts).

RAM (Random Access Memory)

Fast, volatile memory used for data the CPU needs right now. Programs and their variables live in RAM while running. When you turn off the computer, RAM is wiped clean.

ROM (Read-Only Memory)

Non-volatile memory with permanent instructions, like the BIOS/UEFI firmware that starts the boot process. It cannot be easily modified — that's the "read-only" part.

Volatile vs Non-Volatile Memory

VolatileNon-Volatile
Data on power off?LostRetained
SpeedVery fastSlower
ExampleRAMHard drive, SSD, ROM
PurposeActive working memoryPermanent storage

Peripherals

External devices connected to the computer. Input peripherals send data in (keyboard, mouse, microphone). Output peripherals display results (monitor, speakers, printer). Some are both — like a touchscreen.

Computer Software & Programming Languages

Software is the set of instructions that tells hardware what to do. Programming languages are how humans write those instructions.

Low-Level Programming Languages

Close to the hardware. Machine code (binary 1s and 0s) is the lowest — it's what the CPU actually executes. Assembly language is one step up, using short mnemonics like MOV, ADD, JMP. Fast but hard for humans to read and write.

High-Level Programming Languages

Closer to human language. Java, Python, C++ — these are high-level. They must be translated into machine code before the CPU can run them. Much easier to write, read, and maintain. Java is the language used on the AP CSA exam.

Binary Digit (Bit)

The smallest unit of data in computing. A bit is a single 0 or 1. Everything in a computer — numbers, text, images, your Java programs — is ultimately represented as sequences of bits. Why binary? Because electronic circuits have two states: on (1) and off (0).

Number Systems & Base Conversion

We normally count in base 10 (decimal) because we have 10 fingers. Computers use base 2 (binary). Programmers also use base 8 (octal) and base 16 (hexadecimal) as shorthand for binary.

Common Bases

BaseNameDigitsExample
2Binary0, 11010 = 10 in decimal
8Octal0 - 712 = 10 in decimal
10Decimal0 - 910
16Hexadecimal0 - 9, A - FA = 10 in decimal

Converting Decimal to Binary

Divide by 2 repeatedly, record the remainders, then read them bottom to top.

Example: Convert 13 to binary
13 / 2 = 6  remainder 1
 6 / 2 = 3  remainder 0
 3 / 2 = 1  remainder 1
 1 / 2 = 0  remainder 1
                      ↑ read bottom-to-top
13 in decimal = 1101 in binary

Converting Binary to Decimal

Multiply each digit by its place value (powers of 2) and add them up.

Example: Convert 1101 to decimal
Position:  3    2    1    0
Binary:    1    1    0    1
Value:     2³   2²   2¹   2⁰
         = 8  + 4  + 0  + 1  = 13

In Java

Java — Number literals in different bases
int decimal     = 13;      // base 10 (normal)
int binary      = 0b1101;  // base 2  (prefix 0b)
int octal       = 015;     // base 8  (prefix 0)
int hexadecimal = 0xD;     // base 16 (prefix 0x)

// All four variables hold the same value: 13
System.out.println(decimal);      // 13
System.out.println(binary);       // 13
System.out.println(octal);        // 13
System.out.println(hexadecimal);  // 13

Measuring Memory

Memory is measured in bits and bytes. Everything scales by powers of 2 (in computer science) or powers of 10 (in marketing — watch out for that on the exam).

UnitSizeApprox. Real-World
1 Bit0 or 1A single yes/no answer
1 Byte8 bitsA single character (like 'A')
1 Kilobyte (KB)1,024 bytesA short email
1 Megabyte (MB)1,024 KBA photo or short song
1 Gigabyte (GB)1,024 MB~250 songs or a short movie
1 Terabyte (TB)1,024 GB~500 hours of video

Java Source Code Structure

Every Java program needs at minimum: a class and a main method. The file name must match the class name exactly (including capitalization) and end in .java.

HelloWorld.java — The minimum required structure
public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, AP CSA!");
    }

}

Breaking it down

PartMeaning
publicAccessible from anywhere
class HelloWorldDefines a class named HelloWorld (must match file name)
{ }Curly braces define the body of the class / method
public static void main(String[] args)The entry point — Java starts running here
System.out.println(...)Prints text to the console with a newline
;Every statement in Java ends with a semicolon

Comments in Java

Comments are notes for humans. The compiler ignores them completely. Use them to explain why code exists, not what it does (the code itself should show that).

Java — Two styles of comments
// This is a single-line comment.
// Everything after // on this line is ignored.

/*
   This is a multi-line comment.
   It can span as many lines as you need.
   Great for longer explanations.
*/

/**
 * This is a Javadoc comment.
 * Used to generate documentation for classes and methods.
 * You'll see these in the AP Quick Reference sheet.
 */
public class CommentDemo {
    public static void main(String[] args) {
        System.out.println("Comments are ignored by the compiler");
        // System.out.println("This line won't run — it's commented out");
    }
}

Quick Reference

TypeSyntaxUse Case
Single-line// commentShort notes, disabling one line
Multi-line/* comment */Longer explanations, block-disable code
Javadoc/** comment */API documentation for classes/methods

3 Types of Errors

When code doesn't work, the error falls into one of three categories. Knowing which type you're dealing with tells you where andhow to fix it.

1. Compile / Syntax Error

The code violates Java's grammar rules. The compiler catches these before the program runs. You literally cannot run the program until these are fixed.

Example — missing semicolon
System.out.println("Hello")
//                              ^ missing ;
// Compiler error:
// ';' expected

2. Runtime Error (Exception)

The code compiles fine, but crashes while running. The program terminates with an exception message. Common causes: dividing by zero, accessing a null object, array index out of bounds.

Example — division by zero
int x = 10;
int y = 0;
System.out.println(x / y);
// Compiles fine, but crashes:
// ArithmeticException: / by zero

3. Runtime Error (Logic)

The code compiles and runs without crashing, but produces the wrong result. No error message — the program just does the wrong thing. These are the hardest to find.

Example — wrong formula
// Goal: average of 3 scores
int a = 80, b = 90, c = 100;
double avg = a + b + c / 3;
System.out.println(avg);
// Prints 203.0 — not 90.0!
// Bug: division happens before
// addition (operator precedence).
// Fix: (a + b + c) / 3.0

Compiler vs Interpreter

High-level code must be translated into something the machine understands. There are two main strategies:

CompilerInterpreter
How it worksTranslates the entire program at once, producing an output fileTranslates and runs the program one line at a time
Error detectionReports all syntax errors before runningStops at the first error it encounters
SpeedSlower to compile, faster to runNo compile step, but slower execution
OutputA separate executable or bytecode fileNo separate file — runs directly
ExamplesJava (javac), C, C++Python, JavaScript

Java uses both. The javac compiler translates your .java source into bytecode (.class files). Then the JVM interprets (or JIT-compiles) that bytecode at runtime.

Java Virtual Machine & Bytecode

This is Java's superpower: "Write once, run anywhere."

📄HelloWorld.javaSource code (you write this)
javac compilerChecks syntax, translates to bytecode
📦HelloWorld.classBytecode (platform-independent)
JVM (java)Interprets bytecode for your OS
💻OutputHello, AP CSA!

Why bytecode?

Bytecode is not machine code — it's an intermediate format that any JVM can understand. So the same .class file runs on Windows, macOS, or Linux without recompiling. Each platform just needs its own JVM installed.

Terminal — Compiling and running Java
$ javac HelloWorld.java    # Step 1: compile → creates HelloWorld.class
$ java HelloWorld          # Step 2: run bytecode on the JVM
Hello, AP CSA!             # Output

print vs println

Both methods belong to the PrintStream class (accessed via System.out). The only difference: does the cursor move to the next line after printing?

MethodNewline after?Usage
System.out.print()NoKeeps cursor on the same line
System.out.println()YesMoves cursor to the next line after printing
PrintDemo.java
public class PrintDemo {
    public static void main(String[] args) {

        // println moves to the next line after each call
        System.out.println("Line 1");
        System.out.println("Line 2");

        System.out.println(); // prints a blank line

        // print stays on the same line
        System.out.print("Hello ");
        System.out.print("World");
        System.out.println("!"); // finishes the line

        // Mixing them together
        System.out.print("A");
        System.out.println("B");
        System.out.print("C");
        System.out.print("D");
    }
}
Output
Line 1
Line 2

Hello World!
AB
CD

AP Exam Tip

The AP exam loves asking you to predict the output of code that mixes print and println. Trace through each statement and track where the cursor is. Pay close attention to spaces — they only appear if you explicitly include them in the string.

Tracing exercise — What does this print?
System.out.print("AP");
System.out.println(" CSA");
System.out.print("Unit ");
System.out.print(1);
System.out.println();
System.out.println("Done!");
Answer
AP CSA
Unit 1
Done!