Java basics: classes, main, and output
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
AP Computer Science A uses Java
- The AP CSA exam is written in Java.
- Java is strict: every program lives inside a class, and starts from a method called main.
- You already think like a programmer — here we learn Java's rules.
The Java skeleton
- A tiny Java program looks like the example below. Your code goes inside main.
System.out.println(...)prints one line of text (like Python'sprint).- Every statement ends with a semicolon
;.
public class Main {
public static void main(String[] args) {
System.out.println("Java runs from inside main.");
int year = 12;
System.out.println("Grade " + year);
}
}
Types
- Java needs a type for every variable:
int(whole number),double(decimal),boolean(true/false),String(text). - You write the type first:
int score = 10;. - Join text and values with
+:"Grade " + yearmakesGrade 12.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Inside main, use System.out.println(...) to print exactly Hello, AP CSA!
Click Run to see the output here.
Complete the method square(int n) so it returns n * n. The checker calls it with several values.
Click Run to see the output here.