Java Foundations and Program Design

A practical introduction to Java program structure, data types, operators, input and output, problem-solving strategy, testing, and debugging for AP Computer Science A.

Programming as problem solving

AP Computer Science A uses Java to develop a repeatable process for solving problems. The central task is to translate a question into an algorithm, implement that algorithm, and verify that the result is correct.

A productive programming cycle is:

  1. Understand the required input, output, and rules.

  2. Plan the algorithm using ordinary language, pseudocode, or a diagram.

  3. Implement the plan in Java.

  4. Test typical, boundary, and unusual cases.

  5. Debug errors and improve clarity.

  6. Explain why the solution works.

A program is not complete merely because it compiles. Correctness also requires producing the intended result for valid inputs.

Takeaway: Plan before coding, test after coding, and treat explanation and debugging as part of programming rather than as optional steps.

Java program structure

A basic Java application is organized around a class and a . For example, the statement public class Greeting declares a class, while public static void main(String[] args) identifies where execution begins.

Important structural elements include:

  • Braces, written as { and }, enclose blocks of code.

  • A semicolon, written as ;, ends a statement.

  • System.out.println(...) displays a value and then moves to a new line.

  • Text in double quotation marks is a String literal.

  • A public class normally uses the same name as its source file, such as Greeting.java for Greeting.

Comments are ignored by the compiler but can explain purpose, assumptions, or non-obvious reasoning. Java supports single-line comments beginning with //, multiline comments enclosed by /* and */, and documentation comments beginning with /**.

An import statement makes a library class available by its short name. For example, import java.util.; allows a program to refer to without writing its fully qualified name. Importing a class does not execute it.

Takeaway: Classes organize Java code, the is the entry point, and careful structure makes programs easier to read and maintain.

Variables and data types

A is a named storage location with a type and a current value. Declaration introduces the , while assignment stores a value in it. For example, int score; declares a and score = 95; assigns a value. These operations can be combined as int attempts = 3;.

A later assignment replaces the previous value. If int x = 4; is followed by x = 10;, the value of x becomes 10. A local must receive a value before it is used.

Choose names that communicate purpose, such as numberOfStudents, averageScore, and isComplete. Java conventionally uses lower camel case for and method names, while class names use UpperCamelCase. A fixed value can be declared with final, as in final double TAX_RATE = 0.0825;.

The most common introductory data types are:

  • int for whole numbers such as -7, 0, and 42.

  • double for decimal values such as 3.14.

  • boolean for true or false.

  • char for one character, written with single quotation marks, such as 'A'.

  • String for text, written with double quotation marks, such as "Java".

A directly represents a value. A stores a reference to an object. Selecting an appropriate type helps Java detect invalid operations and makes the program's purpose clearer.

Takeaway: Every needs an appropriate type, a meaningful name, and a value before use.

Expressions and operators

An combines values, variables, operators, and sometimes method calls to produce a value. Java evaluates arithmetic according to precedence: multiplication and division occur before addition and subtraction unless parentheses change the order.

The main arithmetic operators are:

  • + for addition

  • - for subtraction

  • * for multiplication

  • / for division

  • % for the

is important. When both operands are integers, 7/27 / 2 produces 33 because the fractional part is discarded. Using a decimal operand, as in 7.0 / 2, produces a decimal result of 3.53.5. The is useful for tasks such as identifying even numbers: number % 2 == 0.

Compound assignment makes updates concise. score = score + 5; and score += 5; have the same effect. The operators ++ and -- increase or decrease a value by one.

The + operator also concatenates strings. In "Maya scored " + points + " points.", Java converts the numeric value of points to text as part of the result. Parentheses are important when arithmetic is combined with concatenation, as in "Average: " + (first + second) / 2.0.

Casting explicitly converts a value to another type. For example, (int) price removes the fractional portion of a double; it does not round to the nearest integer. Avoid unnecessary casts because they can lose precision.

Takeaway: Know operator precedence, distinguish from decimal division, and use parentheses when mixed operations could be misunderstood.

Input, output, and simple algorithms

The pattern describes many beginner programs. A program first reads data, then calculates or transforms it, and finally displays a result.

System.out.print(...) displays text without automatically moving to a new line, while System.out.println(...) displays text and then moves to the next line. Formatted output such as System.out.printf("Cost: $%.2f%n", cost); can control the number of displayed decimal places.

reads tokens from standard input. Common methods include:

  • nextInt() for an integer

  • nextDouble() for a decimal number

  • nextBoolean() for true or false

  • next() for the next whitespace-delimited token

  • nextLine() for the rest of the current line

A common input issue occurs when nextInt() or nextDouble() is followed by nextLine(). The numeric method may leave the line break in the input buffer, so an additional nextLine() may be needed before reading the intended line. Input must also match the requested type; supplying nonnumeric text to nextInt() can cause the input operation to fail.

For a minutes-conversion problem, gives the whole hours and the remainder gives the leftover minutes. With totalMinutes as the input, the calculations are hours = totalMinutes / 60 and minutes = totalMinutes % 60. For an input of 135, the result is 2 hours and 15 minutes.

Takeaway: Match each input method to the expected data and separate reading, processing, and displaying into clear steps.

Testing, tracing, and debugging

Testing checks whether an algorithm works beyond one convenient example. For the minutes-conversion problem, useful cases include:

  • A typical case: 135 should produce 2 hours and 15 minutes.

  • A boundary case: 60 should produce 1 hour and 0 minutes.

  • A small case: 5 should produce 0 hours and 5 minutes.

  • An additional case: 0 should produce 0 hours and 0 minutes.

A trace table records how values change as statements execute. For an input of 135, the initial totalMinutes is 135; after hours = totalMinutes / 60, hours is 2; after minutes = totalMinutes % 60, minutes is 15. Tracing is especially useful when code runs but produces an unexpected result.

A is detected before execution. Missing semicolons, unmatched braces, undeclared variables, and assigning text to an integer are examples. A occurs while the program runs; invalid input and division by zero are examples. A allows the program to run but produces the wrong result, such as using when a decimal result is intended.

Good debugging habits include reading compiler messages carefully, checking assumptions, tracing variables, testing boundary cases, using meaningful names, indenting consistently, and preferring clear code over clever code.

Takeaway: Test representative and boundary inputs, then use traces and error categories to locate the cause of a failure.