1.3 Expressions and Output

From CS Awesome 2CC BY-NC-SA 4.0Original page

Java1 class period7 exercises10 graded tests

Files

README.mdDownload

1.3 Expressions and Output

Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.

Output

Java has two different methods to print output to the screen:

  • System.out.println(value) : prints the value followed by a new line (ln)
  • System.out.print(value) : prints the value without advancing to the next line

System.out.println("Hi there!"); prints out the characters between the first " and the second " followed by a new line. The "Hi there!" is called a string literal which is zero to many characters enclosed in starting and ending double quotes. A literal is the code representation of a fixed value, which can be a string or a numerical value.

Exercise 1

Run this code to see its output. How would you change it to print the ! on the same line as Hi there keeping all 3 print statements?

Open the 01-printCommands folder and edit MyClass.java. Press Run to try it; Run Tests checks it (2 tests).

What if you wanted to print out a double quote " character? Since " is a special character with a meaning in Java string literals, we put in a backslash (\") in front of the quote to signal that we want just the quote character. This is called a backslash escape sequence. And if you wanted to print out a backslash, you would have to backslash (\\) it too in order to escape its special meaning. Another useful backslashed character is \n which will put in a newline.

Exercise 2

Here are the escape sequences that may be used in the AP course.

Open the 02-bhescape folder and run TestEscape.java. It is an example, so it has no tests.

Expressions and Operators

Arithmetic Expressions consist of numeric values, variables, and arithmetic operators that evaluate to a single numerical value. For example, the expression 2 + 3 evaluates to 5.

Java uses the standard mathematical operators for addition (+), subtraction (-), and division (/). The multiplication operator is written as *, as it is in most programming languages, since the character sets used until relatively recently didn’t have a character for a real multiplication sign, ×, and keyboards still don’t have a key for it. For similar reasons the ÷ symbol is not used in Java. (You may have noticed that + was also used to combine String and other values into new Strings. More on this later.)

Arithmetic expressions can be of type int or double. An arithmetic expression consisting only of int values will evaluate to an int value. An arithmetic expression that uses at least one double value will evaluate to a double value. This means that when you are doing division with two integers, you will get an integer result and the decimal part of the result will be thrown away. This is called truncating division. If you want a double result, you should make at least one of the values in the expression a double like 2.0.

Exercise 3

Run the code to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3? Isn’t it surprising that it prints 0? See the note above about truncating division with integers. Change the code to make it print the decimal part of the division too. You can do this by making at least one of the numbers a double like 2.0.

Open the 03-lcop1 folder and edit Test1.java. Press Run to try it; Run Tests checks it (1 test).

Math errors sometimes lead to runtime errors in code. For example, when the Hubble Space Telescope was launched to space in 1990, a math coding error in a formula caused it to point in the wrong direction! It missed its target stars by about half a degree which is about the width of the moon seen from Earth (https://scholar.lib.vt.edu/VA-news/ROA-Times/issues/1990/rt9005/900510/05100615.htm). Thorough testing is the only way to make sure there are no logic errors that will cause runtime errors in your code. Try the following example that tries to convert centimeters to inches. Can you fix the runtime error?

Exercise 4

The code is trying to convert centimeters to inches, but it has a math error. Run the code to see that there are no error messages, but it simply does the wrong calculation! Can you fix the logic error in the code? 1 inch = 2.54 cms.

Open the 04-cm2in-runtime-error folder and edit CmToInches.java. Press Run to try it; Run Tests checks it (2 tests).

Another runtime error that is possible in math expressions is dividing by zero which is undefined in mathematics. An attempt to divide an integer by the integer 0 will result in an ArithmeticException in Java, as we saw in the first lesson. Try it in one of the exercises to see what happens.

Compound Expressions

Expressions can be combined into compound expressions with multiple operators. When compound expressions are evaluated, operator precedence rules are used, just like when we do math (remember PEMDAS?), so that multiplication *, division /, and remainder % are done before addition + and subtraction -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first or just to make it more clear.

Exercise 5

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence. How do the parentheses change the precedence?

Open the 05-compound1 folder and run TestCompound.java. It is an example, so it has no tests.

The Remainder Operator

The operator % in Java is the remainder operator. Like the other arithmetic operators it takes two operands. Mathematically it returns the remainder after dividing the first number by the second, using truncating integer division. For instance, 5 % 2 evaluates to 1 since 2 goes into 5 two times with a remainder of 1.

While you may not have heard of remainder as an operator, think back to elementary school math when you first learned long division, before you learned about decimals. You probably learned how to give the answer to a long division that didn’t divide evenly in terms of the number of even divisions and the remainder. The remainder is what is returned by the % operator. In the figures below, the remainders are the same values that would be returned by 2 % 3 and 5 % 2.

Long division showing the integer result and the remainder

Long division showing the integer result and the remainder

Sometimes people—including Professor Lewis in the next video—will call % the modulo, or mod, operator. That is not actually correct though the difference between remainder and modulo, which uses Euclidean division instead of truncating integer division, only matters when negative operands are involved and the signs of the operands differ. With positive operands, remainder and mod give the same results. Java does have a method Math.floorMod in the Math class if you need to use modulo instead of remainder, but % is all you need in the AP exam.

Here’s the video.

Exercise 6

In the example below, try to guess what it will print out and then run it to see if you are right.

Open the 06-lcop2 folder and run Test1.java. It is an example, so it has no tests.

The result of x % y when x is smaller than y is always x. The value y can’t go into x at all (goes in 0 times), since x is smaller than y, so the result is just x. So if you see 2 % 3 the result is 2.

Check your understanding: What is the result of 158 % 10? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-3-expressions.html#mcq-rem1

Check your understanding: What is the result of 3 % 8? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-3-expressions.html#mcq-rem2

Coding Challenge: Pay Calculator

Dollar Sign

In this coding challenge, you can work in pairs to create a pay calculator using math expressions and operators.

Exercise 7

Complete the following expressions for a pay calculator.

Open the 07-challenge1-3-pay-calculator folder and edit Challenge1_3_Pay_Calculator.java. Press Run to try it; Run Tests checks it (5 tests).

Summary

  • (AP 1.3.A.1) System.out.print and System.out.println are Java output statements that display information on the computer screen. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
  • (AP 1.3.B.1) A literal is the code representation of a fixed value, which can be a string or a numerical value.
  • (AP 1.3.B.2) A string literal is a sequence of zero to many characters enclosed in starting and ending double quotes.
  • (AP 1.3.B.3) Escape sequences are special sequences of characters that can be included in a string. They start with a backslash \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline\n.
  • (AP 1.3.C.1) Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
  • (AP 1.3.C.2) The arithmetic operators consist of +, -, * , /, and % also known as addition, subtraction, multiplication, division, and remainder.
  • (AP 1.3.C.2) An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away.
  • (AP 1.3.C.2) An arithmetic operation that uses at least one double value will evaluate to a double value.
  • (AP 1.3.C.3) When dividing numeric values that are both int values, the result is only the integer portion of the quotient. Anything after the decimal point is thrown away. When dividing numeric values that use at least one double value, the result is the double quotient as expected.
  • (AP 1.3.C.4) The remainder (modulo) operator % is used to compute the remainder when one number is divided by another number.
  • (AP 1.3.C.5) Multiple operators can be used to combine expressions into compound expressions.
  • (AP 1.3.C.5) During evaluation, numeric values are associated with operators according to operator precedence to determine how they are grouped. *, /, % have precedence over + and -, unless parentheses are used to group those to be evaluated first. Operators with the same precedence are evaluated from left to right.
  • (AP 1.3.C.6) An attempt to divide an integer by zero will result in an ArithmeticException.

AP Practice

Check your understanding: Consider the following code segment.

System.out.print("Java is ");
System.out.println("fun ");
System.out.print("and cool!");

What is printed as a result of executing the code segment?

Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-3-expressions.html#AP1-3-1

Check your understanding: Consider the following code segment.

System.out.println(5 + 5 / 2 * 3 - 1);

What is printed when the code segment is executed?

Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-3-expressions.html#apcsa_sample1_exp

For teachers

1.3 Expressions and Output

Students read CSAwesome2's “Expressions and Output” in CS Room and work through its 7 Java coding exercises (4 graded, 3 examples).

  • Time: 1 class period
  • Tests: 10 in 4 graded exercises, set up for you when you import the lesson

Goals

  • (AP 1.3.A.1) System.out.print and System.out.println are Java output statements that display information on the computer screen. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
  • (AP 1.3.B.1) A literal is the code representation of a fixed value, which can be a string or a numerical value.
  • (AP 1.3.B.2) A string literal is a sequence of zero to many characters enclosed in starting and ending double quotes.
  • (AP 1.3.B.3) Escape sequences are special sequences of characters that can be included in a string. They start with a backslash \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline\n.
  • (AP 1.3.C.1) Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
  • (AP 1.3.C.2) The arithmetic operators consist of +, -, * , /, and % also known as addition, subtraction, multiplication, division, and remainder.
  • (AP 1.3.C.2) An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away.
  • (AP 1.3.C.2) An arithmetic operation that uses at least one double value will evaluate to a double value.
  • (AP 1.3.C.3) When dividing numeric values that are both int values, the result is only the integer portion of the quotient. Anything after the decimal point is thrown away. When dividing numeric values that use at least one double value, the result is the double quotient as expected.
  • (AP 1.3.C.4) The remainder (modulo) operator % is used to compute the remainder when one number is divided by another number.
  • (AP 1.3.C.5) Multiple operators can be used to combine expressions into compound expressions.
  • (AP 1.3.C.5) During evaluation, numeric values are associated with operators according to operator precedence to determine how they are grouped. *, /, % have precedence over + and -, unless parentheses are used to group those to be evaluated first. Operators with the same precedence are evaluated from left to right.
  • (AP 1.3.C.6) An attempt to divide an integer by zero will result in an ArithmeticException.

Before class

In class

  1. Students read README.md. Questions that need CS Awesome's interactive widgets link back to it.
  2. Students do exercises 01–07, each in its own folder, pressing Run to try their code.
  3. Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.

Exercises

FolderFileGradingTests
01-printCommandsMyClass.javaAutograded2
02-bhescapeTestEscape.javaExample, not graded0
03-lcop1Test1.javaAutograded1
04-cm2in-runtime-errorCmToInches.javaAutograded2
05-compound1TestCompound.javaExample, not graded0
06-lcop2Test1.javaExample, not graded0
07-challenge1-3-pay-calculatorChallenge1_3_Pay_Calculator.javaAutograded5

Teachers can download a reference solution after signing in.