Ch1-7 Flashcards
One of the components of a computer is its CPU. What is a CPU and what role does it play in a computer?
The CPU, or Central Processing Unit, is the active part of the computer. Its function is to execute programs that are coded in machine language and stored in the main memory (RAM) of the computer. It does this by repeating the fetch-and-execute cycle over and over; that is, it repeatedly fetches a machine language instruction from memory and executes it.
Explain what is meant by an “asynchronous event.” Give some examples.
An asynchronous event is one that occurs at an unpredictable time outside the control of the program that the CPU is running. It is not “synchronized” with the program. An example would be when the user presses a key on the keyboard or clicks the mouse button. (These events generate “interrupts” that cause the CPU to interrupt what it is doing and to take some action to handle the asynchronous event. After handling the event, the CPU returns to what it was doing before it was interrupted.)
What is the difference between a “compiler” and an “interpreter”?
Compilers and interpreters have similar functions: They take a program written in some programming language and translate it into machine language. A compiler does the translation all at once. It produces a complete machine language program that can then be executed. An interpreter, on the other hand, just translates one instruction at a time, and then executes that instruction immediately. (Java uses a compiler to translate java programs into Java Bytecode, which is a machine language for the imaginary Java Virtual Machine. Java Bytecode programs are then executed by an interpreter.)
Explain the difference between high-level languages and machine language.
Programs written in the machine language of a given type of computer can be directly executed by the CPU of that type of computer. High-level language programs must be translated into machine language before they can be executed. (Machine language instructions are encoded as binary numbers that are meant to be used by a machine, not read or written by people. High-level languages use a syntax that is closer to human language.)
If you have the source code for a Java program, and you want to run that program, you will need both a compiler and an interpreter. What does the Java compiler do, and what does the Java interpreter do?
The Java compiler translates Java programs into a language called Java bytecode. Although bytecode is similar to machine language, it is not the machine language of any actual computer. A Java interpreter is used to run the compiled Java bytecode program. (Each type of computer needs its own Java bytecode interpreter, but all these interpreters interpret the same bytecode language.)
What is a subroutine?
A subroutine is a set of instructions for performing some task that have been grouped together and given a name. Later, when that task needs to be performed, it is only necessary to call the subroutine by giving its name, rather than repeating the whole sequence of instructions.
Java is an object-oriented programming language. What is an object?
An object consists of some data together with a set of subroutines that manipulate that data. (An object is a kind of “module,” or self-contained entity that communicates with the rest of the world through a well-defined interface. An object should represent some coherent concept or real-world object.)
What is a variable? (There are four different ideas associated with variables in Java. Try to mention all four aspects in your answer. Hint: One of the aspects is the variable’s name.)
A variable is a 1.memory location that has been given a 2.name so that it can easily be referred to in a program. The variable holds a 3.value, which must be of some specified 4.type. The value can be changed during the course of the execution of the program.
Java is a “platform-independent language.” What does this mean?
A Java program can be compiled once into a Java Bytecode program. The compiled program can then be run on any computer that has an interpreter for the Java virtual machine. Other languages have to be re-compiled for each platform on which they are going to run. The point about Java is that it can be executed on many different types of computers without being recompiled.
What is the “Internet”? Give some examples of how it is used. (What kind of services does it provide?)
The Internet is a network connecting millions of computers around the world. Computers connected to the Internet can communicate with each other. The Internet can be used for Email (which lets a user of one computer send a message to a user on another computer), file sharing (which is used to copy files between computers), and the World Wide Web (which lets a user view “pages” of information published on computers around the world).
Briefly explain what is meant by the syntax and the semantics of a programming language. Give an example to illustrate the difference between a syntax error and a semantics error.
The syntax of a language is its grammar, and the semantics is its meaning. A program with a syntax error cannot be compiled. A program with a semantic error can be compiled and run, but gives an incorrect result. A missing semicolon in a program is an example of a syntax error, because the compiler will find the error and report it. If N is an integer variable, then the statement “frac = 1/N;” is probably an error of semantics. The value of 1/N will be 0 for any N greater than 1. It’s likely that the programmer meant to say 1.0/N.
What does the computer do when it executes a variable declaration statement. Give an example.
A variable is a “box”, or location, in the computer’s memory that has a name. The box holds a value of some specified type. A variable declaration statement is a statement such as
int x;
which creates the variable x. When the computer executes a variable declaration, it creates the box in memory and associates a name (in this case, x) with that box. Later in the program, that variable can be referred to by name.
What is a type, as this term relates to programming?
A “type” represents a set of possible values. When you specify that a variable has a certain type, you are saying what values it can hold. When you say that an expression is of a certain type, you are saying what values the expression can have. For example, to say that a variable is of type int says that integer values in a certain range can be stored in that variable.
One of the primitive types in Java is boolean. What is the boolean type? Where are boolean values used? What are its possible values?
The only values of type boolean are true and false. Expressions of type boolean are used in places where true/false values are expected, such as the conditions in while loops and if statements.
Give the meaning of each of the following Java operators:
a) ++
b) &&
c) !=
The operator ++ is used to add 1 to the value of a variable. For example, “count++” has the same effect as “count = count + 1”.
The operator && represents the word and. It can be used to combine two boolean values, as in “(x > 0 && y > 0)”, which means, “x is greater than 0 and y is greater than 0.”
The operation != means “is not equal to”, as in “if (x != 0)”, meaning “if x is not equal to zero.”.
Explain what is meant by an assignment statement, and give an example. What are assignment statements used for?
An assignment statement computes a value and stores that value in a variable. Examples include:
x = 17; // Assign a constant value to the variable, x. newRow = row; // Copy the value from the variable, row, // into the variable, newRow. ans = 17*x + 42; // Compute the value of the expression // 17*x + 42, and store that value in ans.
An assignment statement is used to change the value of a variable as the program is running. Since the value assigned to the variable can be another variable or an expression, assignments statements can be used to copy data from one place to another in the computer, and to do complex computations.
What is meant by precedence of operators?
If two or more operators are used in an expression, and if there are no parentheses to indicate the order in which the operators are to be evaluated, then the computer needs some way of deciding which operator to evaluate first. The order is determined by the precedence of the operators. For example, * has higher precedence than +, so the expression 3+57 is evaluated as if it were written 3+(57).
What is a literal?
A literal is a sequence of characters used in a program to represent a constant value. For example, ‘A’ is a literal that represents the value A, of type char, and 17L is a literal that represents the number 17 as a value of type long. A literal is a way of writing a value, and should not be confused with the value itself.
In Java, classes have two fundamentally different purposes. What are they?
A class can be used to group together variables and subroutines that are contained in the class. These are called the static members of the class. For example, the subroutine Math.sqrt is a static member of the class called Math. Also, the main routine in any program is a static member of a class. The second possible purpose of a class is to describe and create objects. The class specifies what variables and subroutines are contained in those objects. In this role, classes are used in object-oriented programming (which we haven’t studied yet in any detail.)
What is the difference between the statement “x = TextIO.getDouble();” and the statement “x = TextIO.getlnDouble();”
Either statement will read a real number input by the user, and store that number in the variable, x. They would both read and return exactly the same value. The difference is that in the second statement (using getlnDouble), after reading the value the computer will continue reading characters from input up to and including the next carriage return. These extra characters are discarded.
Explain why the value of the expression 2 + 3 + “test” is the string “5test” while the value of the expression “test” + 2 + 3 is the string “test23”. What is the value of “test” + 2 * 3 ?
The reason is somewhat technical. The difference is due to the order of evaluation. When several + operators are used in a row, with no parentheses, they are evaluated from left to right. 2 + 3 + “test” is interpreted as (2 + 3) + “test”, so 2 and 3 are added together, giving 5, and then the 5 is concatenated onto the string “test”. On the other hand, “test” + 2 + 3 is interpreted as (“test” + 2) + 3, so the 2 is first concatenated onto the “test”, giving “test2”, and then the 3 is concatenated onto that. In the case of “test” + 2 * 3, the precedence rules for + and * come into play. Since * has higher precedence, this expression is interpreted as “test” + (2 * 3), which evaluates to “test6”.
Integrated Development Environments such as Eclipse often use syntax coloring, which assigns various colors to the characters in a program to reflect the syntax of the language. A student notices that Eclipse colors the word String differently from int, double, and boolean. The student asks why String should be a different color, since all these words are names of types. What’s the answer to the student’s question?
Although String, like int, double, and boolean, is a type name, there is a fundamental difference between String and the other types. String is the name of a class, while int, double, and boolean are primitive types. Eclipse colors all class names in the same way that it does String, and it uses a different color for the primitive types. (Although the difference between classes and primitive types might not seem very important to you now, it really is an important distinction and it’s reasonable for Eclipse to use different colors for the two concepts.)
What is an algorithm?
An algorithm is an unambiguous, step-by-step procedure for performing a certain task, which is guaranteed to finish after a finite number of steps. (An algorithm is not the same thing as a program, but it can be the idea behind a program.)
Explain briefly what is meant by “pseudocode” and how is it useful in the development of algorithms.
Pseudocode refers to informal descriptions of algorithms, written in a language that imitates the structure of a programming language, but without the strict syntax. Pseudocode can be used in the process of developing an algorithm with stepwise refinement. You can start with a brief pseudocode description of the algorithm and then add detail to the description through a series of refinements until you have something that can be translated easily into a program written in an actual programming language.
What is a block statement? How are block statements used in Java programs?
A block statement is just a sequence of Java statements enclosed between braces, { and }. The body of a subroutine is a block statement. Block statements are often used in control structures. A block statement is generally used to group together several statements so that they can be used in a situation that only calls for a single statement. For example, the syntax of a while loop calls for a single statement: “while (condition) do statement”. However, the statement can be a block statement, giving the structure: “while (condition) { statement; statement; …}”.
What is the main difference between a while loop and a do..while loop?
Both types of loop repeat a block of statements until some condition becomes false. The main difference is that in a while loop, the condition is tested at the beginning of the loop, and in a do..while loop, the condition is tested at the end of the loop. It is possible that the body of a while loop might not be executed at all. However, the body of a do..while loop is executed at least once since the condition for ending the loop is not tested until the body of the loop has been executed.
What does it mean to prime a loop?
The condition at the beginning of a while loop has to make sense even the first time it is tested, before the body of the loop is executed. To prime the loop is to set things up before the loop starts so that the test makes sense (that is, the variables that it contains have reasonable values). For example, if the test in the loop is “while the user’s response is yes,” then you will have to prime the loop by getting a response from the user (or making one up) before the loop.
Explain what is meant by an animation and how a computer displays an animation.
An animation consists of a series of “frames.” Each frame is a still image, but there are slight differences from one frame to the next. When the images are displayed rapidly one frame after another, the eye perceives motion. A computer displays an animation by showing one image on the screen, then replacing it with the next image, then the next, and so on.
Write a for loop that will print out all the multiples of 3 from 3 to 36, that is: 3 6 9 12 15 18 21 24 27 30 33 36.
Here are two possible answers. Assume that N has been declared to be a variable of type int:
for ( N = 3; N <= 36; N = N + 3 ) { System.out.println( N ); }
or for ( N = 3; N <= 36; N++ ) { if ( N % 3 == 0 ) System.out.println( N ); }
Fill in the following main() routine so that it will ask the user to enter an integer, read the user’s response, and tell the user whether the number entered is even or odd. (You can use TextIO.getInt() to read the integer. Recall that an integer n is even if n % 2 == 0.)
public static void main(String[] args) {
// Fill in the body of this subroutine!
}
:
The problem already gives an outline of the program. The last step, telling the user whether the number is even or odd, requires an if statement to decide between the two possibilities.
public static void main (String[] args) {
int n; // the number read from the user
TextIO.put(“Type an integer: “); // ask the use to enter an integer
n = TextIO.getInt(); // read the user’s response
if (n % 2 == 0) // tell the user whether the number is even or odd
System.out.println(“That’s an even number.”);
else
System.out.println(“That’s an odd number.”);
}
Write a code segment that will print out two different random integers selected from the range 1 to 10. All possible outputs should have the same probability. Hint: You can easily select two random numbers, but you have to account for the fact that the two numbers that you pick might be the same.
The code for selecting two random integers has to be wrapped in a loop that will end only when the two selected numbers are different. This can be done easily with a do..while loop. A while loop can also be used, but it must be “primed” in some way. Note that by using a loop to choose the numbers, we can be absolutely sure that after the loop ends, the two numbers are different. Here are three possible solutions:
(1) int x,y; // Two random integers.
do {
x = (int)(10Math.random() + 1);
y = (int)(10Math.random() + 1);
} while (x == y); // continue if x and y are the same number.
System.out.println(x + “ “ + y);
(2) int x,y; // Two random integers.
x = y = 0; // Give them junk value to “prime” the loop to make sure it runs.
while (x == y) {
x = (int)(10Math.random() + 1);
y = (int)(10Math.random() + 1);
}
System.out.println(x + “ “ + y);
(3) int x,y; // Two random integers.
x = (int)(10Math.random() + 1); // Pick x, and keep its value.
do { // The loop finds a y with a different value from x.
y = (int)(10Math.random() + 1);
} while (x == y);
System.out.println(x + “ “ + y);
Suppose that s1 and s2 are variables of type String, whose values are expected to be string representations of values of type int. Write a code segment that will compute and print the integer sum of those values, or will print an error message if the values cannot successfully be converted into integers. (Use a try..catch statement.)
The function Integer.parseInt can be used to convert the strings into integers. This function will throw an exception of type NumberFormatException if the conversion fails. A try..catch statement can catch this exception and print an error message. So, the code segment can be written:
try {
int n1, n2; // The values of s1 and s2 as integers.
int sum; // The sum of n1 and n2.
n1 = Integer.parseInt(s1);
n2 = Integer.parseInt(s2);
sum = n1 + n2; // (If an exception occurs, we don’t get to this point.)
System.out.println(“The sum is “ + sum);
}
catch ( NumberFormatException e ) {
System.out.println(“Error! Unable to convert strings to integers.);
}
Show the exact output that would be produced by the following main() routine:
public static void main(String[] args) { int N; N = 1; while (N <= 32) { N = 2 * N; System.out.println(N); } }
The exact output printed by this program is:
2 4 8 16 32 64
(The hard part to get right is the 64 at the end. The value of N doubles each time through the loop. For the final execution of the loop, N starts out with the value 32, but N is doubled to 64 before it is printed.)
Show the exact output produced by the following main() routine:
public static void main(String[] args) { int x,y; x = 5; y = 1; while (x > 0) { x = x - 1; y = y * x; System.out.println(y); } }
The way to answer this question is to trace exactly what the program does, step-by-step. The output is shown below on the right. On the left is a table that shows the values of the variables x and y as the program is being executed.
value of x | value of y OUTPUT
————–|————– ————-
5 | 1 [ before loop]
4 | 4 [ = 14 ] 4
3 | 12 [ = 43 ] 12
2 | 24 [ = 122 ] 24
1 | 24 [ = 241 ] 24
0 | 0 [ = 24*0 ] 0