Program Structure and Output
Explain the anatomy of a Java program: class declaration, main method signature, statements, and semicolons. Distinguish System.out.println (newline), System.out.print (no newline), and System.out.printf (formatted). Use escape sequences (\n, \t, \", \\). Distinguish the three error types: syntax errors (compiler), runtime errors (crash during execution), and logic errors (wrong output, no crash). Trace simple programs line-by-line and predict exact console output.
A lesson of AP Computer Science A, in Java Foundations, about 10 minutes.
Java Program Structure and Output
By the end of this lesson, you will be able to write a complete Java program, produce output using print statements, and understand the structure of a Java class.
Anatomy of a Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Key elements:
public class HelloWorld— declares a class named HelloWorld. The filename MUST match the class name exactly (HelloWorld.java).public static void main(String[] args)— the entry point; execution starts here.System.out.println(...)— prints to the console; adds a newline at the end.
Print Statements
System.out.println("Hello"); // prints "Hello" then newline
System.out.print("Hi "); // prints "Hi " (no newline)
System.out.print("there!"); // prints on the same line → "Hi there!"
System.out.println(); // prints just a newline
System.out.println(value): prints the value followed by a newline.
System.out.print(value): prints the value WITHOUT a newline.
System.out.printf(format, args): formatted output.
String Concatenation in Output
String name = "Alice";
int age = 17;
System.out.println("Name: " + name + ", Age: " + age);
// Output: Name: Alice, Age: 17
Use + to combine strings and variables:
Watch: adding a number to a string vs. adding numbers:
System.out.println(1 + 2 + " hi"); // → "3 hi" (adds numbers first)
System.out.println("hi " + 1 + 2); // → "hi 12" (concatenates left to right)
Comments
// This is a single-line comment
/* This is a
multi-line comment */
/** This is a Javadoc comment — for documentation */
Comments are ignored by the compiler. Good comments explain WHY, not WHAT.