Expressions and Output
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];
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.
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.
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
intvalues results in anint. - An operation with at least one
doublevalue results in adouble.
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 / 2evaluates to3.57 / 2.0evaluates to3.57.0 / 2.0evaluates to3.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 % 2evaluates to1(because 7 divided by 2 is 3, with a remainder of 1).10 % 3evaluates to1(10 divided by 3 is 3, with a remainder of 1).12 % 4evaluates to0(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.
- Parentheses
() - Exponents (not on the AP CSA exam)
- Multiplication
*, Division/, Remainder%(from left to right) - 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.)
See it in action
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.
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:
- 1Line 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 number20into the string"20"and joins them. - The expression is now
"The price is $20" + 5. - The same rule applies again. Java converts
5to"5"and concatenates. - The final string for this line is
"The price is $205". - Since this is a
System.out.printstatement, the cursor stays at the end of the line.
- We start with the string literal
- 2Line 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.
- This command prints the string
- 3Line 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
20and5are integers, this is regular addition:20 + 5evaluates to the integer25. - Now the expression is
"Your total is $" + 25. - This is string concatenation. The integer
25is converted to the string"25"and joined. - The final string is
"Your total is $25". - This is printed on the new line.
- This line is different because of the parentheses
Final Output:
The price is $205 (tax included).
Your total is $25
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).
- 1Identify OperatorsWe have
+,/,-,%,*. - 2Precedence Group 1 (Multiplication, Division, Remainder)We evaluate these from left to right.
- First up is
15 / 2. This is integer division! The result is7, not7.5. The.5is truncated.- Expression becomes:
10 + 7 - 3 % 2 * 5
- Expression becomes:
- Next is
3 % 2. The remainder when 3 is divided by 2 is1.- Expression becomes:
10 + 7 - 1 * 5
- Expression becomes:
- Last in this group is
1 * 5, which is5.- Expression becomes:
10 + 7 - 5
- Expression becomes:
- First up is
- 3Precedence Group 2 (Addition, Subtraction)Now we evaluate what's left, again from left to right.
- First is
10 + 7, which is17.- Expression becomes:
17 - 5
- Expression becomes:
- Finally,
17 - 5, which is12.
- First is
Final Answer: The value of result is 12.
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.)
Practice — 8 questions
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.
System.out.print("Hello, ");
System.out.println("Priya!");
System.out.println("Welcome to AP CS A.");
- 1.3.A: Develop code to generate output and determine the result that would be displayed.
- 1.3.B: Develop code to utilize string literals and determine the result of using string literals.
- 1.3.C: Develop code for arithmetic expressions and determine the result of these expressions.
- 1.3.A.1
- System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
- 1.3.B.1
- A literal is the code representation of a fixed value.
- 1.3.B.2
- A string literal is a sequence of characters enclosed in double quotes.
- 1.3.B.3
- Escape sequences are special sequences of characters that can be included in a string. They start with a \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline \n.
- 1.3.C.1
- Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
- 1.3.C.2
- The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value.
- 1.3.C.3
- When dividing numeric values that are both int values, the result is only the integer portion of the quotient. When dividing numeric values that use at least one double value, the result is the quotient.
- 1.3.C.4
- The remainder operator % is used to compute the remainder when one number a is divided by another number b.
- 1.3.C.5
- Operators can be used to construct compound expressions. At compile time, numeric values are associated with operators according to operator precedence to determine how they are grouped. Parentheses can be used to modify operator precedence. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right.
- 1.3.C.6
- An attempt to divide an integer by the integer zero will result in an ArithmeticException.
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];
Read what Saavi narrates
Hello everyone, it's Saavi from Shrutam.
Have you ever looked at a receipt from a store and thought about how it’s made? It has text like "Thank you," and it has numbers and calculations, like the subtotal and tax. That receipt is a perfect example of what we're learning today: how to make our Java programs talk and do math.
We're going to cover how to print information, handle text, and perform calculations correctly. It's the first step in making your code do something you can actually see.
Let's dive into one of the most important, and often trickiest, parts: doing math in Java. Let's say we need to solve a problem. What is the value of an integer variable called 'result' after a line of code like this runs: imagine result is set to ten plus fifteen divided by two, minus three remainder two, times five.
It looks complicated, but we just need to follow the order of operations, or PEMDAS. First, we look for multiplication, division, and remainder, and we solve them from left to right.
The first one is fifteen divided by two. Now, here is the most common mistake. In Java, when you divide two integers, it chops off the decimal. So fifteen divided by two is seven, not seven-point-five. Our expression now becomes... ten plus seven minus three remainder two times five.
Next up is three remainder two. The remainder when you divide three by two is one. So the expression is now... ten plus seven minus one times five.
Then, one times five is five. We're left with... ten plus seven minus five.
Now we just do the addition and subtraction from left to right. Ten plus seven is seventeen. And seventeen minus five is twelve. So, the final result is twelve.
The biggest takeaway here is to watch out for that integer division. It will come up again and again on the AP exam. If you see two whole numbers being divided, remember to truncate the decimal.
You're building a really strong foundation. Keep practicing, don't be afraid to make mistakes, and you will get this. You are more than capable. Keep up the great work!
`print` leaves the cursor on the same line, while `println` moves it to the next. Mixing them up leads to jumbled, unformatted output that won't match what the exam question asks for.
Remember `println` stands for "print line," meaning it prints a full line and then moves on. Use `print` only when you intentionally want to build a single line of output from multiple commands.
When both numbers in a division are integers, Java performs integer division and truncates (chops off) the decimal part. The result of `7 / 2` is `3`.
To get a decimal result, make sure at least one of the numbers is a `double`. For example, write `7.0 / 2` or `(double) 7 / 2`.
`10 + 5` is `15`. But `"Result: " + 10 + 5` is `"Result: 105"`. The `+` operator becomes concatenation as soon as a String is involved in the expression (from left to right).
Use parentheses to force mathematical operations to happen before string concatenation. Write `"Result: " + (10 + 5)` to get `"Result: 15"`.
Calculating `3 + 4 * 2` as `7 * 2 = 14` is incorrect. Java always performs multiplication/division/remainder before addition/subtraction.
Follow PEMDAS strictly. `3 + 4 * 2` becomes `3 + 8`, which is `11`. When in doubt, use parentheses to make the order of operations explicit: `3 + (4 * 2)`.
In Java, double quotes `"` are for `String` literals (e.g., `"Hello"`). Single quotes `'` are for `char` literals (e.g., `'H'`), which can only hold a single character. `System.out.println('Hello')` will not compile.
Always enclose your string literals in double quotes.
Writing `System.out.println("The folder is C:\new");` will not print what you expect. `\n` is the escape sequence for a newline, so the output would be on two lines.
Memorize the key escape sequences: `\"` for a quote, `\\` for a backslash, and `\n` for a newline. The correct code is `System.out.println("The folder is C:\\new");`.