Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Expressions and Output

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, this topic is about how to make your Java program display text and numbers, and how to perform basic math calculations like you would on a calculator.

Why this matters

Think about the last time you got a receipt from a store in Dallas or a coffee shop in Seattle. It’s a perfect little piece of computer output. It has fixed text like "Thank You For Shopping!" and your order details. It also has numbers and calculations: the price of your items, the subtotal, sales tax, and the final amount.

That receipt is exactly what we're learning to create in Java. How do we tell the computer to print specific words? How do we make it do math and show the result? This lesson is your first step toward making your programs communicate and calculate, moving from silent code to programs that can actually show you what they’re doing. We'll cover how to print information, handle text, and perform calculations correctly.

Concept overview

flowchart TD
    A[Start: 10 + 15 / 2 - 3 % 2 * 5] --> B{Identify *, /, % operators};
    B --> C["Evaluate 15 / 2 (integer division) -> 7"];
    C --> D["Expression becomes: 10 + 7 - 3 % 2 * 5"];
    D --> E["Evaluate 3 % 2 -> 1"];
    E --> F["Expression becomes: 10 + 7 - 1 * 5"];
    F --> G["Evaluate 1 * 5 -> 5"];
    G --> H["Expression becomes: 10 + 7 - 5"];
    H --> I{Identify +, - operators};
    I --> J["Evaluate 10 + 7 -> 17"];
    J --> K["Expression becomes: 17 - 5"];
    K --> L["Evaluate 17 - 5 -> 12"];
    L --> M[End: Result is 12];
This diagram is a flowchart that shows the step-by-step evaluation of the Java arithmetic expression "10 + 15 / 2 - 3 % 2 * 5". It demonstrates the order of operations, starting with division and remainder, then multiplication, and finally addition and subtraction, to arrive at the final result of 12.

Core explanation

Alright, let's get our programs talking! A program that does amazing things but never shows you the result isn't very useful. The first step is learning how to generate output.

Displaying Information: Your Program's Voice

In Java, the most common way to display information is with a command that prints to the console, which is that text output area you see when you run your code.

There are two key commands you need to know:

  • System.out.println(): Prints the information you give it, and then moves the cursor to a new line, ready for the next thing. Think of it like hitting "Enter" after typing a line in a text message.
  • System.out.print(): Prints the information you give it, but leaves the cursor right at the end of the printed text. The next print command will start from that exact spot.

Let's see it in action. Imagine you run this code:

System.out.print("Hello, ");
System.out.println("Priya!");
System.out.println("Welcome to AP CS A.");

The output would look like this:

Hello, Priya!
Welcome to AP CS A.
Comparing `System.out.print()` and `System.out.println()` behavior.

Working with Text: String Literals

The text in the double quotes, like "Hello, Priya!", is called a string literal. A literal is just the code representation of a fixed value. 12 is an integer literal, 3.14 is a double literal, and "Welcome" is a string literal. It's "literal" because the value is exactly what you see written in the code.

Visualizing different types of literals in Java.

What if you need to include special characters in your string? For example, what if you want to print a sentence with quotation marks inside it, like: She said, "Hi!"

If you just type System.out.println("She said, "Hi!""), Java will get confused. It sees the second quote before "Hi!" and thinks the string is over. To solve this, we use escape sequences. These are special codes that start with a backslash (\) to tell Java, "Hey, the next character has a special meaning!"

Here are the three you must know for the AP exam:

  • \" — Inserts a double quote.
  • \\ — Inserts a single backslash.
  • \n — Inserts a newline character (like hitting Enter).

So, to print She said, "Hi!", you would write:

System.out.println("She said, \"Hi!\"");

And to print a Windows file path like C:\Users\Jordan, you'd write:

System.out.println("C:\\Users\\Jordan");

Doing the Math: Arithmetic Expressions

Now for the fun part: calculations. Java can handle math with arithmetic expressions, which are just combinations of values (like 5, 10.5), variables, and operators (+, -, *, /, %).

Java has two main number types we care about right now: int for integers (whole numbers) and double for floating-point numbers (numbers with decimals). The type you use matters a lot.

Rule:

  • An operation with two int values results in an int.
  • An operation with at least one double value results in a double.

The basic operators are straightforward:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)

But division is where things get interesting.

Integer Division vs. Double Division

Imagine you have 7 cookies (int 7) and you want to share them equally among 2 friends (int 2). In the real world, you might break a cookie in half. But with integers, you can't have half a cookie! Integers are whole numbers only.

In Java, 7 / 2 evaluates to 3.

It doesn't round. It simply truncates, or chops off, the decimal part. The .5 is thrown away.

Now, if you introduce a decimal (a double), the calculation changes completely.

  • 7.0 / 2 evaluates to 3.5
  • 7 / 2.0 evaluates to 3.5
  • 7.0 / 2.0 evaluates to 3.5

As long as at least one number is a double, Java will perform floating-point division and give you the precise decimal answer.

The Remainder Operator: %

What happened to that leftover cookie in our 7 / 2 integer example? That's where the remainder or modulo operator (%) comes in. It tells you what's left over after an integer division.

  • 7 % 2 evaluates to 1 (because 7 divided by 2 is 3, with a remainder of 1).
  • 10 % 3 evaluates to 1 (10 divided by 3 is 3, with a remainder of 1).
  • 12 % 4 evaluates to 0 (12 divides evenly by 4, so there's no remainder).

This is incredibly useful for problems involving even/odd numbers or cycles.

Order of Operations (PEMDAS/GEMDAS)

Just like in your math class, Java follows an order of operations. You can remember it as PEMDAS or GEMDAS.

  1. Parentheses ()
  2. Exponents (not on the AP CSA exam)
  3. Multiplication *, Division /, Remainder % (from left to right)
  4. Addition +, Subtraction - (from left to right)

The operators *, /, and % have higher precedence than + and -. If you have multiple operators of the same precedence (like * and /), they are evaluated from left to right.

Consider the expression 10 + 5 * 2. Java does the multiplication first (5 * 2 = 10), then the addition (10 + 10 = 20). The result is 20.

If you want to do the addition first, you must use parentheses: (10 + 5) * 2. Now, Java evaluates the parentheses first (10 + 5 = 15), then the multiplication (15 * 2 = 30). The result is 30.

When in doubt, use parentheses! They make your code clearer and guarantee the order you want.

A Word of Warning: Division by Zero

One last thing: what happens if you try to divide by zero? In integer arithmetic, like 17 / 0, the universe breaks. Your program will crash and give you an ArithmeticException. You cannot divide an integer by zero. Just remember that.

(Interestingly, dividing a double by zero gives you Infinity, but that's a detail you don't need to worry about for now. The exam focuses on the integer case.)

Correctly using escape sequences for special characters in strings.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of examples to see these rules in practice. It’s one thing to read them, and another to apply them.

    Example 1

    Predicting Print Output

    Problem: What is the exact output of the following code snippet?

    System.out.print("The price is $" + 20 + 5);
    System.out.println(" (tax included).");
    System.out.println("Your total is $" + (20 + 5));

    Solution Walkthrough:

    1. 1
      Line 1
      System.out.print("The price is $" + 20 + 5);
      • We start with the string literal "The price is $".
      • Next, Java sees + 20. This is the tricky part. When you use + with a string and a number, Java performs string concatenation, not addition. It converts the number 20 into the string "20" and joins them.
      • The expression is now "The price is $20" + 5.
      • The same rule applies again. Java converts 5 to "5" and concatenates.
      • The final string for this line is "The price is $205".
      • Since this is a System.out.print statement, the cursor stays at the end of the line.
    2. 2
      Line 2
      System.out.println(" (tax included).");
      • This command prints the string " (tax included).".
      • Because the cursor was waiting at the end of the previous output, this string gets printed on the same line.
      • The line now reads: "The price is $205 (tax included).".
      • This is a println, so the cursor now moves to the next line.
    3. 3
      Line 3
      System.out.println("Your total is $" + (20 + 5));
      • This line is different because of the parentheses (20 + 5).
      • Thanks to the order of operations, the expression inside the parentheses is evaluated first. Since both 20 and 5 are integers, this is regular addition: 20 + 5 evaluates to the integer 25.
      • Now the expression is "Your total is $" + 25.
      • This is string concatenation. The integer 25 is converted to the string "25" and joined.
      • The final string is "Your total is $25".
      • This is printed on the new line.

    Final Output:

    The price is $205 (tax included).
    Your total is $25
    Example 2

    Integer Arithmetic Deep Dive

    Problem: What is the value of the integer variable result after this line of code executes?

    int result = 10 + 15 / 2 - 3 % 2 * 5;

    Solution Walkthrough:

    Let's break this down using the order of operations (PEMDAS/GEMDAS).

    1. 1
      Identify Operators
      We have +, /, -, %, *.
    2. 2
      Precedence Group 1 (Multiplication, Division, Remainder)
      We evaluate these from left to right.
      • First up is 15 / 2. This is integer division! The result is 7, not 7.5. The .5 is truncated.
        • Expression becomes: 10 + 7 - 3 % 2 * 5
      • Next is 3 % 2. The remainder when 3 is divided by 2 is 1.
        • Expression becomes: 10 + 7 - 1 * 5
      • Last in this group is 1 * 5, which is 5.
        • Expression becomes: 10 + 7 - 5
    3. 3
      Precedence Group 2 (Addition, Subtraction)
      Now we evaluate what's left, again from left to right.
      • First is 10 + 7, which is 17.
        • Expression becomes: 17 - 5
      • Finally, 17 - 5, which is 12.

    Final Answer: The value of result is 12.

    Tracing string concatenation vs. arithmetic addition with `+` operator.
    Avoiding the common mistake of unexpected string concatenation.

    Try it yourself

    Ready to test your skills? Here are a couple of problems to try on your own.

    1. Predict the Output

    What is the exact output of the following Java code? Pay close attention to print vs. println and the escape sequences.

    public class OutputPractice {
        public static void main(String[] args) {
            System.out.print("Item\tPrice\n");
            System.out.println("----\t----");
            System.out.print("Book\t$");
            System.out.println(14 + 5);
            System.out.println("Path: \"C:\\Program Files\\Java\"");
        }
    }

    (Hint: \t is another escape sequence that acts like the Tab key. Even though it's not required for the exam, see if you can figure out how it affects the spacing! The rest of the problem uses only the concepts we covered.)

    2. Write the Expression

    A movie ticket in Chicago costs $15. A bucket of popcorn costs $9. You are buying tickets for yourself and n friends (so, n + 1 people total) and you will all share one bucket of popcorn.

    Write a single Java arithmetic expression to calculate the total cost. Assume you have an integer variable n that holds the number of friends.

    (Hint: Use parentheses to group the number of people correctly before multiplying by the ticket price.)

    Flowchart for determining output based on `print` vs `println`.