3 Primitive Types

AP Computer Science A Prep, 2024 - Rob Franek 2023

3 Primitive Types
Part V: Content Review for the AP Computer Science A Exam

Computer Science (CS) is an official name used for many aspects of computing, usually on the developing end; its areas include computer programming, which is exactly what you will be doing in AP Computer Science A (APCS). APCS focuses on the language Java and its components, and in many cases, you will be the programmer. Although the person using your program (the user) will typically see only the end result of your program, CS gives you the tools to write statements (code) that will ideally make the user’s experience both functional and enjoyable.

PROGRAMMING STYLE

Computer programming is similar to a foreign language; it has nouns, verbs, and other parts of speech, and it has different forms of style, just like verbal languages. Just as you might use different words and ways of speaking—tone, expressions, etc.—with your family versus your friends, CS has many different languages and, within each language, its own ways of getting the job done. In both the CS world and the APCS world, a particular programming style is expected in order to show fluency in the language. A company that might hire you for a CS job will likely expect you to conform to its own unique programming style; similarly, the College Board will expect you to conform to its accepted programming style based on its research of CS styles accepted at universities around the world.

Comments, Identifiers, White Space

Commenting is an extremely vital style technique in the programming world. Comments do not actually cause the program to behave any differently; however, comments serve many purposes, including:

· allowing programmers to make “notes” within the program that they may want to reference later

· allowing the person reading and/or using the program (“the reader” and/or “the user”) to understand the code in a less cryptic way, when applicable

· revealing to the programmer/reader/user aspects of the program that are required to make the program operate as intended and/or are produced as a result of the program’s execution

There are two types of commenting in Java. In-line, or short, comments appear after or near a statement and are preceded by two forward slashes (“//”) followed by the comment. Long comments that extend beyond a single line of code are surrounded by special characters; they begin with (“/*”) and end with (“*/”).

For example,

// This is a short comment

/* This is a

long comment */

Identifiers are names that are given to represent data stored in the memory of the computer during the program’s execution. Rather than using a nonsensical memory address code to reference data, Java allows the programmer to name an identifier to perform this job. When we name identifiers in Java, there are guidelines that we must use and guidelines that the College Board expects us to use:

· An identifier may contain any combination of letters, numbers, and underscore (“_”), but must begin with a letter and may not contain any other characters than these, including spaces.

· An identifier should be a logical name that corresponds to the data it is associated with; for example, an identifier associated with the side of a triangle would be more useful as side1 instead of s.

· An identifier should begin with a lowercase letter and, if it is composed of several words, should denote each subsequent word with a capital letter. If we decided to create an identifier associated with our triangle’s number of sides, numberOfSides or numOfSides would conform to this style; NumberOfSides and numofsides would not.

White space is another element of style that does not affect the overall functionality of the program. Rather, it enhances the readability of the program by allowing the programmer to space out the code to separate specific statements or tasks from others. Much like a book may leave empty space at the end of a chapter and begin the next chapter on the next page without affecting the overall story, white space has a similar effect.

Compiling & Errors

When the programmer writes Java code, statements are written that are understood within a Java development environment. The computer, however, does not understand this language, much like you would likely not understand a foreign language that you have never studied, spoken in its native environment. Therefore, an interpreter is used within the developer environment, enabling the computer to understand the Java code. A computer operates using code written only in binary (zeroes and ones, literally!), and so the interpreter “translates” your Java code into binary. This process is called compiling. As a result, in most instances as well as on the AP Exam, modern computer programmers do not need to understand binary code directly.

When an interactive development environment (“IDE”) is used to compile your code, the code will be automatically checked for basic programming errors. If an error is found within the code, the compiling is halted, and an error message is produced (this feedback is where the “interactive” part comes in); this situation is called a compile-time error. Although the error message/code is not always helpful in a direct way, it does allow the programmer to troubleshoot the issue in a more directed way. Unfortunately, since the AP Exam is a pencil-and-paper test, you will have access to neither a computer nor a compiler. Your code must be absent of errors in order to receive full credit for the response (or any credit if it’s a multiple-choice question).

A logical error is more difficult to troubleshoot, as opposed to a problem with the syntax of the Java code itself. A logical error lies in the desired output/purpose of the program. Similar to ordering dinner and receiving a perfectly prepared dessert instead, you are getting a good result, but it is not appropriate for the desired task.

A run-time error is an error that is not caught by the compiler, yet produces an error during the execution of the program. In many ways, this is the worst (and most embarrassing) error for the programmer, because it is not realized until the task is supposedly “done.” An example might be a crash that occurs when you are editing your favorite image in a graphics program. It’s frustrating for the user and annoying for the programmer when you leave negative feedback on the company’s website!

Image

1.Assuming all other statements in the program are correct, each of the following statements will allow the program to compile EXCEPT

(A) // This is a comment

(B) /* This is a comment */

(C) // myName is a good identifier name

(D) // myname is a good identifier name

(E) All of the above statements will compile.

Here’s How to Crack It

Choices (A), (B), and (C) are all valid comments in Java, regardless of their contents and the fact that (B) is not actually any longer than a single line. Choice (D) uses a poor identifier name, not a good one, but this situation will not result in a non-compiling program. Therefore, (E) is correct.

Image

OBJECTS & PRIMITIVE DATA

Output (and Some Input)

In order for your program to “do anything” from the user’s perspective (at this level, anyway!), it must produce output to the screen. A program may produce output to many devices, including storage drives and printers, but APCS requires us to produce output only to the screen.

Image

Bonus Tips and Tricks…

Check us out on YouTube for additional test-taking tips and must-know strategies at www.youtube.com/ThePrincetonReview

There are two similar statements that we use to produce output to the screen in this course:

System.out.print(…);

System.out.println(…);

The ellipses in these statements stand for the data and/or identifiers that will be displayed on the screen. We will see the difference between these statements in a minute.

For example, if a triangle has a side length of 2 stored in the memory using the identifier side1 and we wanted to output that information to the screen, we could use one of the following two commands:

System.out.print(2);

System.out.print(side1);

Since both 2 and side1 represent numerical values, they can be outputted to the screen in this way. If we wanted to display non-numerical data, however, we would use a string literal (or simply a string) to accomplish this task. A string literal is simply one or more characters combined into a single unit. The previous sentence, and this sentence, can be considered string literals. In a Java program, string literals must be surrounded by double quotes (“”) to avoid a compile error. In our triangle example, we can use a string literal to make the output more user-friendly:

System.out.println(“The length of side 1 is:”);

System.out.print(side1);

// side1 may be simply substituted with 2, in this case

Note the usage of the println statement rather than the print statement. While print will display the next output on the same line, println will output the string literal and then put the cursor at the beginning of the next line for further output. Note, also, that the statement

System.out.print(side1);

will display the value stored using the side1 identifier, 2. In contrast, the statement

System.out.print(“side1”);

will literally display

side1

because the double quotes create a string literal here. The College Board loves to ask multiple-choice questions that determine whether you understand these differences.

If quotation marks are how programmers signal the beginning and end of a string literal, how would they display quotation marks? For example, what if an instructional program was intended to display

Be sure to display the value of side1, not “side 1”.

The command below might seem like an appropriate solution but would actually cause a compile-time error.

System.out.print(“Be sure to display the value of side1, not “side 1”.”);

The complier will interpret the quotation mark in front of side1 as the close of the string and will not know what to do with the rest of it. To display a quotation mark, the programmer must use an escape sequence, a small piece of coding beginning with a backslash (\) used to indicate specific characters. To successfully display the above live, use the command

System.out.print(“Be sure to print the value of side1, not \“side1\”.”);

Similarly, the escape sequence \n can be used to create a line break in the middle of a string. For example the command

System.out.print(“The first line\nThe second line”);

will display

The first line

The second line

So if a backslash indicates an escape sequence, how does a programmer print a backslash? This is done using another escape sequence, \\. The following command

System.out.println(“Use \\n to indicate a new line.”);

will display

Use \n to indicate a new line.

There are other escape sequences in Java, but only these three appear on the AP Computer Science A Exam.

Image

2.Assuming all other statements in the program are correct, each of the following statements will allow the program to compile EXCEPT

(A) System.out.print(1);

(B) System.out.print(“1”);

(C) System.out.print(side1);

(D) System.out.print(“side1”);

(E) All of the above statements will compile.

Here’s How to Crack It

Choices (A) and (B) will both display 1, although (A) is numerical and (B) is a string literal. Choice (D) will display the string literal side1. Since there is no indication in the question that side1 has been associated with any data, (C) will generate an error because Java does not know what to display. Therefore, (C) is the answer. Be very careful when choosing “all of the above” or “none of the above” answer choices, as these are often trap answers!

Image

As you might imagine, input is also important in programming. Although you may learn some techniques for getting user input (the Scanner class, for example), the AP Exam will not test any input methods or classes. Instead, the input will be assumed and given as a comment in the coding. It may be similar to this.

int k = …, //read user input

You will not be asked to prompt the user for input, unless there is pre-existing code in the task that does it for you. Nice.

Variables & Assignment

Let’s put those identifiers to work.

In order to actually “create” an identifier, we need to assign a data value to that identifier. This task is done by writing an assignment statement.

The syntax of an assignment statement is

type identifier = data;

Continuing with our triangle example, if we wanted to actually assign the data value of 2 to a new identifier called side1, we could use this statement:

int side1 = 2;

This statement tells the compiler that (1) our identifier is called side1, (2) the data assigned to that identifier should be 2, and (3) our data is an integer (more on this in the next section). The equals sign (“=”) is called an assignment operator and is required by Java. The semicolon, which we also saw in the output statements above, denotes that the statement is finished. Note that an assignment statement does NOT produce any output to the screen.

When data is associated with an identifier, the identifier is called a variable. The reason we use this term is that, as in math, the value of the variable can be changed; it can vary! Look at the following code:

int myFavoriteNumber = 22;

myFavoriteNumber = 78;

System.out.print (“My favorite number is ” + myFavoriteNumber);

Can you predict the output? The variable myFavoriteNumber is first assigned the value of 22, but it is then reassigned to the value 78. Therefore, the original value is no longer stored in the computer’s memory and the 78 remains. The output would be

My favorite number is 78

A few items to note in this example:

· Once a variable is given a type (again, more on this later), its type should not be restated. This fact explains why the second assignment statement is missing int.

· The string literal is outputted as written, but the variable’s value, not its name, is outputted.

· In order to output a string literal and a numerical value using the same output statement, use the concatenation operator between the two items. Although this operator looks like a typical + sign, it does not “add” the values in the traditional sense; instead, it simply outputs the two values next to each other. For example, two plus two equals four in the mathematical sense, but 2 concatenated with 2 produces 22.

Image

3.Assuming all other statements in the program are correct, each of the following statements will allow the program to compile EXCEPT

(A) System.out.print(“Ilove Java”);

(B) System.out.println(“Ilove” + “Java”);

(C) System.out.print(1 + “love” + Java”);

(D) System.out.println(1 + “love” + “Java”);

(E) System.out.print(“I love” + “ ” + “Java”);

Here’s How to Crack It

Image

Choices (A) and (B), although their output may not look grammatically correct (they love to do this on the AP Exam—remember, it’s not a grammar test!), will compile without error. Choice (D) is fine because the numerical value is concatenated with the string literals, producing a string literal that can be displayed. Choice (E) uses a string literal that is simply an empty space, which is valid. Therefore, (C) is the answer because “Java” is missing the left-hand quotation mark.

Image

The Four Data Types—int, double, boolean, char

When programmers want to assign data to a variable, they must first decide what type of data will be stored. For the AP Exam, there are four data types that make up the primitive data forms—i.e., the basic types of data. More complex data forms will be discussed later.

integer (int) represents an integer number: positive numbers, negative numbers, and zero, with no decimals or fractions. Integers can store non-decimal values from —2,147,483,648 to 2,147,483,647, inclusive. That’s a lot of values.

double (double) represents a number that can be positive, negative, or zero, and can be a fraction or decimal…pretty much any number you can think of. It also has a much bigger breadth of upper and lower limits than an integer; it can express numbers with decades of significant digits. If you have to store an integer that is larger than the limits listed above, you must store the data as a double.

On the AP Exam, you do not have to memorize the upper and lower limits of these numerical data types; you do, however, need to know that a double must be declared for a number that is larger than an integer can store.

boolean (boolean) represents a value that is either true or false. In machine code, true is represented by 1 (or any nonzero value) and false is represented by 0. This data type is excellent for storing or using yes/no data, such as the responses to: Are you hungry? Are you excited about the AP Exam? Is this chapter boring?

character (char) represents any single character that can be represented on a computer; this type includes any character you can type on the keyboard, including letters, numbers, spaces, and special characters such as slashes, dashes, and the like. char values are stored using a single quotation mark or apostrophe (’). The values of the capital letters A through Z are 65—90 and lowercase letters are 97—122 (browse unicode-table.com/en for a fancier, more complete listing of these values). Although the AP Exam does not require the memorization of these codes (thankfully), you should know their relative placement in the table. For example, you should know that character “A” comes before (has a lower numerical value) than character “B”; you should also note that every capital letter character comes before the lowercase letters. Therefore, “a” actually comes after “Z.”

Image

You’ve Got Character, The Test Doesn’t

It’s useful to know how char works, but it won’t be on the AP Exam, so don’t stress over it!

Arithmetic Operations

The most primitive uses for the first computers were to perform complex calculations. They were basically gigantic calculators. As a result, one of the most basic operations we use in Java involves arithmetic.

The symbols +, -, *, and / represent the operations addition, subtraction, multiplication, and division, respectively. The operator % is also used in Java: called the “modulus” operator, this symbol will produce the numerical remainder of a division. For example, 5 % 2 would evaluate to 1, since 5 divided by 2 yields 2, with 1 as a remainder. These operations can be performed intuitively on numerical values; they can also be performed on variables that store numerical values.

Speaking of math, back to our triangle example….

Consider the following statement in a program:

int side2 = 2, side3 = 3;

(Note that you can write multiple assignment statements in a single line, as long as the data types are the same.)

If we wanted to write a statement that found the sum of these data and assigned the result to another variable called sumOfSides, we could easily write

sumOfSides = 2 + 3; // method 1

But this statement is less useful than

sumOfSides = side2 + side3; // method 2

Since the data is assigned to variables, for which values can vary, method 2 will reflect those changes while method 1 will not.

This same technique can be applied to all of the mathematical operators. Remember that a mixture of mathematical operations follows a specific order of precedence. Java will perform the multiplication and division operations (including modulus), from left to right, followed by the addition and subtraction operations in the same order. If programmers want to change the order of precedence of the operators, they can use parentheses.

Consider these lines of code:

System.out.print(3 - 4/5); // statement 3

System.out.print(3 -(4/5)); // statement 4

System.out.print((3 - 4)/5); // statement 5

In statement 3, the division occurs first, followed by the subtraction (3 minus the answer).

In statement 4, the same thing happens, so it is mathematically equivalent to statement 3.

In statement 5, the parentheses override the order of operations, so the subtraction occurs, and then the answer is divided by 5.

Okay, here’s where it gets crazy. Can you predict the output of these statements? Believe it or not, the output of statements 3 and 4 is 3; the output of statement 5 is 0. These results demonstrate the fact that data in Java is strongly typed.

When you perform a mathematical operation on two integers, Java will return the answer as an integer, as well. Therefore, although 4/5 is actually 0.8, Java will return a value of 0. Likewise, Java will evaluate 5/4 to be 1. The decimal part is cut off (not rounded), so that the result will also be an integer. Negative numbers work the same way. Java will return —4/5 as 0 and —5/4 as —1. Strange, huh?

As is true with all computer science, there is a workaround for this called casting. Casting is a process through which data is forced to “look like” another type of data to the compiler. Think of someone who is cast in a show to play a part; although actors have personal identities, they assume new identities for the audience. The following modifications to statement 3 demonstrate different ways of casting:

System.out.print(3 - (double)(4)/5); // statement 3.1

System.out.print(3 - 4/(double)5); // statement 3.2

These statements will cast 4 and 5, respectively, to be double values of 4.0 and 5.0. As a result, the division will be “upgraded” to a division between double values, not integers, and the desired result will be returned. The following statements, although they will compile without error, will not display the desired result of 2.2.

System.out.print((double)3 - 4/5); // statement 3.3

System.out.print(3 - (double)(4/5)); // statement 3.4

Casting has a higher precedence than arithmetic operators, except parentheses, of course. Therefore, statement 3.3 will first convert 3 to 3.0, but will then perform integer division before completing the subtracting. The result is 3.0. In statement 3.4, the result of dividing the integers is cast to a double; since the integer division evaluates to 0, the cast will simply make the result 0.0, yielding an output of 3.0 once again. Very tricky!

The increment operator (++) is used to increase the value of a number by one. For example, if the value of a variable x is 3, then x++ will increment the value of x to 4. This has the exact same effect as writing x = x + 1, and is nothing more than convenient shorthand.

Conversely, the decrement operator (--) is used to quickly decrease the value of a number by one. For example, if the value of a variable named x is 3, then x-- decreases the value of x to 2. This has the exact same effect as writing x = x - 1.

Other shortcut operators include +=, -=, *=, /=, and %=. These shortcuts perform the indicated operation and assign the result to the original variable. For example,

a += b;

is an equivalent command to

a = a + b;

If int a has been assigned the value 6 and int b has been assigned the value 3, the following table indicates the results of the shortcut operations.

Shortcut Command

Equivalent Command

Resulting value of a

a += b

a = a + b

9

a -= b

a = a - b

3

a *= b

a = a * b

18

a /= b

a = a / b

2

a %= b

a = a % b

0

Image

4.Consider the following code segment:

int a = 3;

int b = 6;

int c = 8;

int d = a / b;

c /= d;

System.out.print(c);

Which of the following will be output by the code segment?

(A) 4

(B) 8

(C) 12

(D) 16

(E) There will be no output because of a run-time error.

Here’s How to Crack It

Go through the coding one step at a time. The first three lines initialize a as 3, b as 6, and c as 8. The fourth line initializes d as a / b, which is 3 / 6. However, note that this is integer division, so the result must be an integer. In normal arithmetic 3 / 6 = 0.5. In Java, integer division cuts off the decimal part, so that d is 0. The command c /= d is equivalent to c = c / d. However, this requires dividing by 0, which is not allowed in Java (or normal arithmetic, for that matter). In Java, dividing by 0 will cause an ArithmeticException, which is a type of run-time error, so the answer is (E).

Image

Give Me a Break

Humans are pretty smart when it comes to guessing intent For instance, you might have noticed that there’s a missing period between this sentence and the one before it. (If not, slow down: AP Computer Science A Exam questions require close reading when looking for errors.) Computers, on the other hand, are literal—more annoyingly so, probably, than those teachers who ask whether you’re physically capable of going to the bathroom when you ask whether you can go. To that end, then, it’s crucial that you end each complete statement (i.e., sentence) with a semicolon, which is our way of telling the Java compiler that it’s reached the end of a step. This doesn’t mean that you need to place a semicolon after every line—remember that line breaks exist only to make code more readable to humans—but you must place one after any complete declaration or statement.

Image

Study Break

Speaking of breaks, don’t burn yourself out and overdo it with your AP Comp Sci preparation. Take it day by day and read a chapter, then work the end-of-chapter drills each day, then every so often, give yourself a break! Go for a walk, call a friend, listen to a favorite song.

KEY TERMS

Computer Science

programming style

commenting

in-line comments (short comments)

long comments

identifiers

white space

interpreter

binary

compiling

compile-time error

logical error

run-time error

string literal (string)

escape sequence

assign

assignment operator

variable

concatenation operator

primitive data

integer

double

boolean

character

precedence

strongly typed

casting

increment operator (++)

decrement operator (--)

CHAPTER 3 REVIEW DRILL

Answers to the review questions can be found in Chapter 13.

1.Consider the following code segment:

1 int a = 10;

2 double b = 10.7;

3 double c = a + b;

4 int d = a + c;

5 System.out.println(c + “ ” + d);

What will be output as a result of executing the code segment?

(A) 20 20

(B) 20.0 30

(C) 20.7 31

(D) 20.7 30.7

(E) Nothing will be printed because of a compile-time error.

2.Consider the following code segment:

1 int a = 10;

2 double b = 10.7;

3 int d = a + b;

Line 3 will not compile in the code segment above. With which of the following statements could we replace this line so that it compiles?

I.    int d = (int) a + b;

II. int d = (int) (a + b);

III. int d = a + (int) b;

(A) I only

(B) II only

(C) III only

(D) I and III only

(E) II and III only

3.Consider the following code segment.

1 int a = 11;

2 int b = 4;

3 double x = 11;

4 double y = 4;

5 System.out.print(a / b);

6 System.out.print(“, ”);

7 System.out.print(x / y);

8 System.out.print(“, ”);

9 System.out.print(a / y);

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

(A) 3, 2.75, 3

(B) 3, 2.75, 2.75

(C) 2, 3, 2

(D) 2, 2.75, 2.75

(E) Nothing will be printed because of a compile-time error.

4.Consider the following statement:

int i = x % 50;

If x is a positive integer, which of the following could NOT be the value of i after the statement above executes?

(A) 0

(B) 10

(C) 25

(D) 40

(E) 50

Summary

o Good use of commenting, identifiers, and white space does not affect the execution of the program but can help to make the program coding easier to interpret for both the programmer and other readers.

o Compilers turn the Java code into binary code. Invalid code will prevent this and cause a compile-time error.

o Logical errors do not prevent the program from compiling but cause undesired results.

o Run-time errors also do not prevent the program from compiling but instead cause the program to halt unexpectedly during execution.

o The AP Computer Science A Exam uses System.out.print() and System.out.println() for output. Any input is assumed and does not need to be coded by the student.

o Variables must be initialized with a data type. They are assigned values using the “=” operator.

o The primitive data types that are tested are int, double, and boolean. String is a non-primitive type that is also tested extensively.

o The int and double operators +, -, *, /, and % are tested on the AP Computer Science A Exam.

o Additional math operations can be performed using the Math class.

o The “+” is used to concatenate strings.