Java basics: classes, main, and output
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.
- This site compiles Java with Java 8 language rules. Our standalone examples define a class with a main entry method. A helper class or an AP method answer does not need its own
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).- Declarations such as
int score = 10;, assignments, method calls andreturnstatements end with a semicolon;. Anif,fororwhileblock uses braces; do not add a semicolon just because its closing brace appears.
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.
Common mistakes
- Use
;after a declaration, assignment, method call orreturn; a block is not another such statement. - For these Java 8 standalone programs, use
public static void main(String[] args). The parameter nameargscan change, andString... argsis also valid. Keep the entry method public, static, returning void and accepting a string array.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- For a complete program, Run compiles and runs it. A method-only task has no Run button: use Check answer to compile it with the supplied harness and check the results.
- Your code compiles and runs on the server. Function tasks use the supplied harness to call your method.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Inside main, use System.out.println(...) to print exactly Hello, AP CSA!
Click Run to see the output here.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
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.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
+ joins text and numbers. The variables name and grade are set for you. Print exactly Ada is in grade 11 with one println that joins them.
Click Run to see the output here.