Ch1-7 Flashcards

1
Q

One of the components of a computer is its CPU. What is a CPU and what role does it play in a computer?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain what is meant by an “asynchronous event.” Give some examples.

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between a “compiler” and an “interpreter”?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the difference between high-level languages and machine language.

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a subroutine?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Java is an object-oriented programming language. What is an object?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Java is a “platform-independent language.” What does this mean?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the “Internet”? Give some examples of how it is used. (What kind of services does it provide?)

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the computer do when it executes a variable declaration statement. Give an example.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a type, as this term relates to programming?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

One of the primitive types in Java is boolean. What is the boolean type? Where are boolean values used? What are its possible values?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Give the meaning of each of the following Java operators:

a) ++
b) &&
c) !=

A

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.”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain what is meant by an assignment statement, and give an example. What are assignment statements used for?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is meant by precedence of operators?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a literal?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

In Java, classes have two fundamentally different purposes. What are they?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the difference between the statement “x = TextIO.getDouble();” and the statement “x = TextIO.getlnDouble();”

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

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 ?

A

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”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

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?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is an algorithm?

A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Explain briefly what is meant by “pseudocode” and how is it useful in the development of algorithms.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a block statement? How are block statements used in Java programs?

A

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; …}”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the main difference between a while loop and a do..while loop?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does it mean to prime a loop?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Explain what is meant by an animation and how a computer displays an animation.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

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.

A

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 );
        }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

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!

}

A

:

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.”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

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.

A

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)(10
Math.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)(10
Math.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)(10
Math.random() + 1);
} while (x == y);
System.out.println(x + “ “ + y);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

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.)

A

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.);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

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);   
    }
}
A

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.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

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);
   }
}
A

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 [ = 4
3 ] 12
2 | 24 [ = 122 ] 24
1 | 24 [ = 24
1 ] 24
0 | 0 [ = 24*0 ] 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What output is produced by the following program segment? Why? (Recall that name.charAt(i) is the i-th character in the string, name.)

String name;
int i;
boolean startWord;

name = "Richard M. Nixon";
startWord = true;
for (i = 0; i < name.length(); i++) {
   if (startWord)
      System.out.println(name.charAt(i));
   if (name.charAt(i) == ' ')
      startWord = true;
   else
      startWord = false;
}
A

This is a tough one! The output from this program consists of the three lines:

R
M
N

As the for loop in this code segment is executed, name.charAt(i) represents each of the characters in the string “Richard M. Nixon” in succession. The statement System.out.println(name.charAt(i)) outputs the single character name.charAt(i) on a line by itself. However, this output statement occurs inside an if statement, so only some of the characters are output. The character is output if startWord is true. This variable is initialized to true, so when i is 0, startWord is true, and the first character in the string, ‘R’, is output. Then, since ‘R’ does not equal ‘ ‘, startWorld becomes false, so no more characters are output until startWord becomes true again. This happens when name.charAt(i) is a space, that is, just before the ‘M’ is processed and again just before the ‘N’ is processed. In fact whatever the value of name, this for statement would print the first character in name and every character in name that follows a space. (It is almost true that this for statement prints the first character of each word in the string, but something goes wrong when the first character is a space or when there are two spaces in a row. What happens in these cases?)

36
Q

Suppose that numbers is an array of type int[]. Write a code segment that will count and output the number of times that the number 42 occurs in the array.

A

Use a for loop to go through the array and test each array element. If the value is 42, add 1 to a counter:

int count42;  // The number of 42s in the array
count42 = 0;
int i;  // loop control variable
for ( i = 0; i < numbers.length; i++ ) {
    if ( numbers[i] == 42 ) {
        count42++;
    }
}
System.out.println("There were " + count42 + " 42s in the array.")
37
Q

Define the range of an array of numbers to be the maximum value in the array minus the minimum value. Suppose that raceTimes is an array of type double[]. Write a code segment that will find and print the range of raceTimes.

A

We need both the minimum and the maximum value in the array. We can compute both using one for loop.

double max; // maximum value from the array
double min; // minimum value from the array
double range; // the range of the array, max - min
int i; // for-loop variable
max = min = raceTimes[0]; // start with both equal to the first element
for ( i = 1; i < raceTimes.length; i++ ) {
if ( raceTimes[i] > max )
max = raceTimes[i];
if ( raceTimes[i] < min )
min = raceTimes[i];
}
range = max - min;
System.out.println(“The range is “ + range);

38
Q

A “black box” has an interface and an implementation. Explain what is meant by the terms interface and implementation.

A

The interface of a black box is its connection with the rest of the world, such as the name and parameters of a subroutine or the dial for setting the temperature on a thermostat. The implementation refers to internal workings of the black box. To use the black box, you need to understand its interface, but you don’t need to know anything about the implementation.

39
Q

A subroutine is said to have a contract. What is meant by the contract of a subroutine? When you want to use a subroutine, why is it important to understand its contract? The contract has both “syntactic” and “semantic” aspects. What is the syntactic aspect? What is the semantic aspect?

A

The contract of a subroutine says what must be done to call the subroutine correctly and what it will do when it is called. It is, in short, everything a programmer needs to know about the subroutine in order to use it correctly. (It does not include the “insides,” or implementation, of the subroutine.)

The syntactic component of a subroutine’s contract includes the name of the subroutine, the number of parameters, and the type of each parameter. This is the information needed to write a subroutine call statement that can be successfully compiled. The semantic component of the contract specifies the meaning of the subroutine, that is, the task that the subroutine performs. It might also specify limitations on what parameter values the subroutine can process correctly. The semantic component is not part of the program. It is generally expressed in comments.

40
Q

Briefly explain how subroutines can be useful in the top-down design of programs.

A

Top-down refers to starting from the overall problem to be solved, and breaking it up into smaller problems that can be solved separately. When designing a program to solve the problem, you can simply make up a subroutine to solve each of the smaller problems. Then you can separately design and test each subroutine.

41
Q

Discuss the concept of parameters. What are parameters for? What is the difference between formal parameters and actual parameters?

A

Parameters are used for communication between a subroutine and the part of the program that calls the subroutine. If a subroutine is thought of as a black box, then parameters are part of the interface to that black box. Formal parameters are found in the subroutine definition. Actual parameters are found in subroutine call statements. When the subroutine is called, the values of the actual parameters are assigned to the formal parameters before the body of the subroutine is executed.

42
Q

Give two different reasons for using named constants (declared with the final modifier).

A

A constant has a meaningful name, which makes the program easier to read. It’s easier to understand what a name like INTEREST_RATE is for than it is to figure out how a literal number like 0.07 is being used.

A second reason for using named constants is that it’s easy to modify the value of the constant if that becomes necessary. If a literal value is used throughout the program, the programmer has to track down each occurrence of the value and change it. When a constant is used correctly, it is only necessary to change the value assigned to the constant at one point in the program.

A third reason is that using the final modifier protects the value of a variable from being changed. This is especially important for member variables that are accessible from outside the class where they are declared.

43
Q

What is an API? Give an example.

A

An API is an Applications Programming Interface. It is the interface to a “toolbox” of subroutines that someone has written. It tells you what routines are available, how to call them, and what they do, but it does not tell you how the subroutines are implemented. An example is the standard Java API which describes the interfaces of all the subroutines in all the classes that are available in such packages as java.lang and java.awt.

44
Q

Write a subroutine named “stars” that will output a line of stars to standard output. (A star is the character “*”.) The number of stars should be given as a parameter to the subroutine. Use a for loop. For example, the command “stars(20)” would output

A

The subroutine could be written as follows:

static void stars(int numberOfStars) {
     // output a line containing the specified number of stars
   for (int i = 0; i < numberOfStars; i++) {
       System.out.print('*');
   }
   System.out.println();  // output carriage return after the *'s
}
45
Q

Write a main() routine that uses the subroutine that you wrote for Question 7 to output 10 lines of stars with 1 star in the first line, 2 stars in the second line, and so on, as shown below.

*

  • *
  • **
A

The main() routine can use a for loop that calls the stars() subroutine ten times, once to produce each line of output. (An occasional beginner’s mistake in this problem is to rewrite the body of the subroutine inside the main() routine, instead of just calling it by name.) Here is the main routine – which would, of course, have to be put together with the subroutine in a class in order to be used.

public static void main(String[] args) {
int line; // Line number, and also the number of stars on that line.
for ( line = 1; line <= 10; line++ ) {
stars( line );
}
}

46
Q

Write a function named countChars that has a String and a char as parameters. The function should count the number of times the character occurs in the string, and it should return the result as the value of the function.

A

The returned value will be of type int. The function simply uses a for loop to look at each character in the string. When the character in the string matches the parameter value, it is counted.

static int countChars( String str, char searchChar ) {
      // Count the number of times searchChar occurs in
      // str and return the result.
    int i;     // A position in the string, str.
    char ch;   // A character in the string.
    int count; // Number of times searchChar has been found in str.
    count = 0;
    for ( i = 0;  i < str.length();  i++ ) {
        ch = str.charAt(i);  // Get the i-th character in str.
        if ( ch == searchChar )
           count++;
    }
    return count;
}
47
Q

Write a subroutine with three parameters of type int. The subroutine should determine which of its parameters is smallest. The value of the smallest parameter should be returned as the value of the subroutine.

A

I’ll call the subroutine smallest and the three parameters x, y, and z. The value returned by the subroutine has to be either x or y or z. The answer will be x if x is less than or equal to both y and z. The correct syntax for checking this is “if (x <= y && x <= z)”. Similarly for y. The only other remaining possibility is z, so there is no necessity for making any further test before returning z. (In fact, doing so would be an error in Java, since with no “else” clause in the if statement, the compiler cannot determine that the function definitely returns a value in all possible cases.)

static int smallest(int x, int y, int z) {
   if (x <= y &amp;&amp; x <= z) {
      return x;
   }
   else if (y <= x &amp;&amp; y <= z) {
      return y;
   }
   else
      return z;
}

Note: Since a return statement causes the computer to terminate the execution of a subroutine anyway, this could also be written as follows, without the elses:

static int smallest(int x, int y, int z) {
   if (x <= y &amp;&amp; x <= z) {
      return x;
   }
   if (y <= x &amp;&amp; y <= z) {
      return y;
   }
   return z;
}
48
Q

Write a function that finds the average of the first N elements of an array of type double. The array and N are parameters to the subroutine.

A

Note that the array must be passed as a parameter of type double[], and that the value returned by the function will be a double. For the value of N to make sense, it should be in the range 1 up to the length of the array. My answer throws an IllegalArgumentException if N is not in this range:

static double average( double[] numbers, int N ) {
    if ( N < 1 ) {
        throw new IllegalArgumentException("Can't find an average of " +
                       N + " numbers.");
    }
    if ( N > numbers.length ) {
        throw new IllegalArgumentsExcpetion( N + 
                      " is more than the length of the array." );
    }
    int sum = 0;  // the sum of the N numbers
    for ( int i = 0; i < N; N++ ) {
        sum = sum + numbers[i];  // add the i-th number to the sum
    }
    return sum/N;  // Return the average as the value of the function.
}
49
Q

Explain the purpose of the following function, and explain how it works:

static int[] stripZeros( int[] list ) {
    int count = 0;
    for (int i = 0; i < list.length; i++) {
        if ( list[i] != 0 )
            count++;
    }
    int[] newList;
    newList = new int[count];
    int j = 0;
    for (int i = 0; i < list.length; i++) {
        if ( list[i] != 0 ) {
            newList[j] = list[i];
            j++;
        }
    }
    return newList;
}
A

This function makes a copy of its parameter, except that it leaves out all the elements of list that are equal to zero. It builds a new array that contains all the non-zero elements of list, and it returns that array as the value of the function. (Note that this is an example of using an array type as the return type of a function.)

The function creates a new array to be the return value. But to do that, it must know how long to make the array. The first five lines of the function definition count the number of non-zero elements in list. This is how many spaces we need in the new array, so count is used as the length when the new array is created. The remainder of the function goes through the original list and copies elements into newList. An element is copied only if it is non-zero. We have to keep track of how many spaces in newList have been filled so far. That’s what j is for. This is the “partially filled array” pattern from Subsection 3.8.4.

50
Q

Object-oriented programming uses classes and objects. What are classes and what are objects? What is the relationship between classes and objects?

A

When used in object-oriented programming, a class is a factory for creating objects. (We are talking here about the non-static part of the class.) An object is a collection of data and behaviors that represent some entity (real or abstract). A class defines the structure and behaviors of all entities of a given type. An object is one particular “instance” of that type of entity. For example, if Dog is a class, than Lassie would be an object of type Dog.

51
Q

What are instance variables and instance methods?

A

Instance variables and instance methods are what we have been calling “non-static variables” and “non-static subroutines.” That is, they are variables and subroutines that are declared in a class but are not marked as “static.” When a class is loaded into the computer, instance variables and methods do not become part of the class in memory; instead, they become part of each object that is constructed from that class, and each object gets its own copy of the instance variables and methods.

52
Q

Explain carefully what null means in Java, and why this special value is necessary.

A

When a variable is of object type (that is, declared with a class or interface as its type rather than one of Java’s primitive types), the value stored in the variable is not an object. Objects exist in a part of memory called the heap, and the variable holds a pointer or reference to the object. Null is a special value that can be stored in a variable to indicate that it does not actually point to any object.

53
Q

What is a constructor? What is the purpose of a constructor in a class?

A

A constructor is a special kind of subroutine in a class. It has the same name as the name of the class, and it has no return type, not even void. A constructor is called with the new operator in order to create a new object. Its main purpose is to initialize the newly created object, but in fact, it can do anything that the programmer wants it to do.

54
Q

Suppose that Kumquat is the name of a class and that fruit is a variable of type Kumquat. What is the meaning of the statement “fruit = new Kumquat();”? That is, what does the computer do when it executes this statement? (Try to give a complete answer. The computer does several things.)

A

This statement creates a new object belonging to the class Kumquat, and it stores a reference to that object in the variable fruit. More specifically, when the computer executes this statement, it allocates memory to hold a new object of type Kumquat. It calls a constructor, which can initialize the instance variables of the object as well as perform other tasks. A reference to the new object is returned as the value of the expression “new Kumquat()”. Finally, the assignment statement stores the reference in the variable, fruit. So, fruit can now be used to access the new object.

55
Q

What is meant by the terms instance variable and instance method?

A

Instance variables and instance methods are non-static variables and methods in a class. This means that they do not belong to the class itself. Instead, they specify what variables and methods are in an object that belongs to that class. That is, the class contains the source code that defines instance variables and instance methods, but actual instance variables and instance methods are contained in objects. (Such objects are called “instances” of the class.) Thus, instance variables and instance methods are the data and the behaviors of objects.

56
Q

Explain what is meant by the terms subclass and superclass.

A

In object oriented programming, one class can inherit all the properties and behaviors from another class. It can then add to and modify what it inherits. The class that inherits is called a subclass, and the class that it inherits from is said to be its superclass. In Java, the fact that ClassA is a subclass of ClassB is indicated in the definition of ClassA as follows:

class ClassA extends ClassB {…}

57
Q

Modify the following class so that the two instance variables are private and there is a getter method and a setter method for each instance variable:

public class Player {
   String name;
   int score;
}
A

To make a variable private, just add the word “private” in front of each declaration. We need two methods for each variable. One of them returns the value of the variable. The other provides a new value for the variable. The names for these methods should follow the usual naming convention for getter and setter methods. (Note that my setter methods use the special variable this so that I can use the same name for the parameter of the method as is used for the instance variable. This is a very common pattern.)

public class Player {
   private String name;
   private int score;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;  // ("this.name" refers to the instance variable)
   }
   public int getScore() {
      return score;
   }
   public void setScore(int score) {
      this.score = score;
   }
}
58
Q

Explain why the class Player that is defined in the previous question has an instance method named toString(), even though no definition of this method appears in the definition of the class.

A

If a class is not declared to extend any class, then it automatically extends the class Object, which is one of the built-in classes of Java. So in this case, Player is a direct subclass of Object. The Object class defines a toString() method, and the Player class inherits this toString() method from Object. The methods and member variables in a class include not just those defined in the class but also those inherited from its superclass.

59
Q

Explain the term polymorphism.

A

Polymorphism refers to the fact that different objects can respond to the same method in different ways, depending on the actual type of the object. This can occur because a method can be overridden in a subclass. In that case, objects belonging to the subclass will respond to the method differently from objects belonging to the superclass.

(Note: If B is a subclass of A, then a variable of type A can refer to either an object of type A or an object of type B. Let’s say that var is such a variable and that action() is a method in class A that is redefined in class B. Consider the statement “var.action()”. Does this execute the method from class A or the method from class B? The answer is that there is no way to tell! The answer depends on what type of object var refers to, a class A object or a class B object. The method executed by var.action() depends on the actual type of the object that var refers to, not on the type of the variable var. This is the real meaning of polymorphism.)

60
Q

Java uses “garbage collection” for memory management. Explain what is meant here by garbage collection. What is the alternative to garbage collection?

A

The purpose of garbage collection is to identify objects that can no longer be used, and to dispose of such objects and reclaim the memory space that they occupy. If garbage collection is not used, then the programmer must be responsible for keeping track of which objects are still in use and disposing of objects when they are no longer needed. If the programmer makes a mistake, then there is a “memory leak,” which might gradually fill up memory with useless objects until the program crashes for lack of memory.

61
Q

What is an abstract class, and how can you recognize an abstract class in Java.

A

An abstract class is one that cannot be used to create objects. It exists only as a basis for making subclasses, and it expresses all the properties and behaviors that those subclasses have in common. In Java, a class can be marked with the modifier abstract to make it abstract. For example,

abstract public class Vehicle { …

It will then be a syntax error to try to call a “new Vehicle” constructor. (Note: Only a class that has been marked as abstract can contain abstract instance methods.)

62
Q

What is this?

A

“this” is a special variable in Java, which does not have to be declared. Java makes it available automatically in instance methods. It can be used in instance methods, and it holds a reference to the object that contains the method (or, in terms of messages, the object that received the message that is being processed). It provides a way to refer to “this object.” If x is an instance variable, it can also be referred to as this.x within the same class. If doSomething() is an instance method, it can also be called as this.doSomething() within the same class.

63
Q

For this problem, you should write a very simple but complete class. The class represents a counter that counts 0, 1, 2, 3, 4, …. The name of the class should be Counter. It has one private instance variable representing the value of the counter. It has two instance methods: increment() adds one to the counter value, and getValue() returns the current counter value. Write a complete definition for the class, Counter.

A

Here is a possible answer. (Note that the initialization of the instance variable, value, to zero is not really necessary, since it would be initialized to zero anyway if no explicit initialization were provided.)

/**
 * An object of this class represents a counter that counts up from zero.
 */
public class Counter {

private int value = 0; // Current value of the counter.

   /**
    * Add one to the value of the counter.
    */
   public void increment() {  
      value++;
   }
   /**
    * Returns the current value of the counter.
    */
   public int getValue() {    
      return value;
   }

} // end of class Counter

64
Q

This problem uses the Counter class from the previous question. The following program segment is meant to simulate tossing a coin 100 times. It should use two Counter objects, headCount and tailCount, to count the number of heads and the number of tails. Fill in the blanks so that it will do so:

Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0;  flip < 100;  flip++ ) {
   if (Math.random() < 0.5)    // There's a 50/50 chance that this is true.
   \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ ;   // Count a "head".

else

   \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ ;   // Count a "tail". }

System.out.println(“There were “ + ___________________ + “ heads.”);

System.out.println(“There were “ + ___________________ + “ tails.”);

A

The variable headCount is a variable of type Counter, so the only thing that you can do with it is call the instance methods headCount.increment() and headCount.getValue(). Call headCount.increment() to add one to the counter. Call headCount.getValue() to discover the current value of the counter. Note that you can’t get at the value of the counter directly, since the variable that holds the value is a private instance variable in the Counter object. Similarly for tailCount. Here is the program with calls to these instance methods filled in:

Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0; flip < 100; flip++ ) {
if (Math.random() < 0.5) // There’s a 50/50 chance that this is true.
headCount.increment() ; // Count a “head”, using headCount
else
tailCount.increment() ; // Count a “tail”, using tailCount
}
System.out.println((“There were “ + headCount.getValue() + “ heads.”);
System.out.println((“There were “ + tailCount.getValue() + “ tails.”);

65
Q

What is meant by the basetype of an array?

A

The base type of an array refers to the type of the items that can be stored in that array. For example, the base type of the array of type Color[] is Color.

66
Q

What is the purpose of the following variable-arity method? What are the values of same(1,2,3), same(17,17,17,17), and same(2)? Why?

static double same( int... value ) {
    for (int i = 1; i < value.length; i++) {
        if ( value[i-1] != value[i] )
            return false;
    }
    return true;
}
A

This function can be called with any number of integer parameters. It tests whether all of the parameter values are equal. The value of same(1,2,3) is false. The function begins by comparing 1 and 2; since they are not equal, it immediately returns false. The value of same(17,17,17,17) is true. The function compares value[0] with value[1], value[1] with value[2], and value[2] with value[3]. All of these values are 17, so the routine goes through the for loop without returning false, and the “return true” statement after the end of the loop is executed. For same(2), value.length is 1, and the body of the loop is never executed; the return value is true.

67
Q

What does it mean to sort an array?

A

To sort an array means to rearrange the items in the array so that they are in increasing or decreasing order (according to some criterion).

(Note: To be more accurate, we should say “non-decreasing” instead of “increasing” and “non-increasing” instead of “decreasing.” An array can contain duplicate values, and in that case, its elements can’be be put into strictly increasing or strictly decreasing order.)

68
Q

What is the main advantage of binary search over linear search? What is the main disadvantage?

A

The advantage of binary search is that it is much faster. On a list of one million items, linear search would take an average of five hundred thousand steps to find an item, whereas binary search would take only 20 steps. The disadvantage is that binary search only works on a sorted list, so some extra work must be done to sort the list or to keep the list in sorted order as it is created.

69
Q

What is meant by a dynamic array? What is the advantage of a dynamic array over a regular array?

A

A dynamic array is like an array in that it is a data structure that stores a sequence of items, all of the same type, in numbered locations. It is different from an array in that there is no preset upper limit on the number of items that it can contain. This is an advantage in situations where a reasonable value for the size of the array is not known at the time it is created.

70
Q

What does it mean to say that ArrayList is a parameterized type?

A

A class name is a type, but as a parameterized type, ArrayList does not define just one type. Instead, for every object type T, there is a type ArrayList. T is a “type parameter.” An object of type ArrayList is a list that can only hold objects of type T. We can have ArrayList to represent lists of Strings, ArrayList to represent lists of Integers, and so one. The fact that ArrayList is a parameterized type means that we don’t have to create a new class for each type of list.

71
Q

Suppose that a variable strlst has been declared as

ArrayList strlst = new ArrayList();

Assume that the list is not empty and that all the items in the list are non-null. Write a code segment that will find and print the string in the list that comes first in lexicographic order.

A

Strings can be compared for lexicographic order using the compareTo instance method in the String class. We can find the smallest string as follows:

String smallest = strlst.get(0);
for (int i = 1; i < strlist.size(); i++) {
String nextString = strlst.get(i);
if ( nextString.compareTo(smallest) < 0 )
smallest = nextString;
}
System.out.println(“The smallest string lexicographically is “ + smallest);

Alternatively, a for-each loop could be used:

String smallest = strlst.get(0);
for (String item : strlst) {
   if ( item.compareTo(smallest) < 0 ) 
       smallest = item;
}
System.out.println("The smallest string lexicographically is " + smallest)

Not that in this version, the first item in the list is compared to itself as the first step in the loop. There is no easy way to leave that item out of the for-each loop.

72
Q

Show the exact output produced by the following code segment.

char[][] pic = new char[6][6];
for (int i = 0; i < 6; i++)
   for (int j = 0; j < 6; j++) {
      if ( i == j  ||  i == 0  ||  i == 5 )
         pic[i][j] = '*';
      else
         pic[i][j] = '.';
   }
for (int i = 0; i < 6; i++) {
   for (int j = 0; j < 6; j++)
      System.out.print(pic[i][j]);
   System.out.println();
}
A

The output consists of six lines, with each line containing six characters. In the first line, i is 0, so all the characters are *’s. In the last line, i is 5, so all the characters are *’s. In each of the four lines in the middle, one of the characters is a * and the rest are periods. The output is

******
.*....
..*...
...*..
....*.
******

It might help to look at the array items that are printed on each line. Note that pic[row][col] is ‘*’ if row is 0 or if row is 5 or if row and col are equal.

pic[0][0] pic[0][1] pic[0][2] pic[0][3] pic[0][4] pic[0][5]
pic[1][0] pic[1][1] pic[1][2] pic[1][3] pic[1][4] pic[1][5]
pic[2][0] pic[2][1] pic[2][2] pic[2][3] pic[2][4] pic[2][5]
pic[3][0] pic[3][1] pic[3][2] pic[3][3] pic[3][4] pic[3][5]
pic[4][0] pic[4][1] pic[4][2] pic[4][3] pic[4][4] pic[4][5]
pic[5][0] pic[5][1] pic[5][2] pic[5][3] pic[5][4] pic[5][5]

73
Q

Write a complete static method that finds the largest value in an array of ints. The method should have one parameter, which is an array of type int[]. The largest number in the array should be returned as the value of the method.

A

One possible answer is:

public static int getMax(int[] list) {

int max = list[0]; // This is the largest item seen so far.

   for (int i = 1; i < list.length; i++) {
         // Look at each item in the array.  If the item is
         // bigger than max, then set max equal to the item.
       if (list[i] > max)
          max = list[i];
   }

// At this point, max is the largest item in the whole array.

return max;

} // end getMax

(Note that this method throws an exception if the parameter list is null or if it is an array of length 0. The exception is thrown by the line “int max = list[0];”. The reference to list[0] causes a NullPointerException if list is null and an ArrayIndexOutOfBoundsException if the array has length zero.)

74
Q

Suppose that temperature measurements were made on each day of 2014 in each of 100 cities. The measurements have been stored in an array

int[][] temps = new int[100][365];

where temps[c][d] holds the measurement for city number c on the dth day of the year. Write a code segment that will print out the average temperature, over the course of the whole year, for each city. The average temperature for a city can be obtained by adding up all 365 measurements for that city and dividing the answer by 365.0.

A

A pseudocode outline of the answer is

For each city {
Add up all the temperatures for that city
Divide the total by 365 and print the answer
}

Adding up all the temperatures for a given city itself requires a for loop, so the code segment looks like this:

for (int city = 0; city < 100; city++) {
int total = 0; // total of temperatures for this city
for (int day = 0; day < 365; day++)
total = total + temps[city][day];
double avg = total / 365.0; // average temp for this city
System.out.println(“Average temp for city number “
+ city + “ is “ + avg);
}

75
Q

Suppose that a class, Employee, is defined as follows:

class Employee {
   String lastName;
   String firstName;
   double hourlyWage;
   int yearsWithCompany;
}

Suppose that data about 100 employees is already stored in an array:

Employee[] employeeData = new Employee[100];

Write a code segment that will output the first name, last name, and hourly wage of each employee who has been with the company for 20 years or more. Write two versions of the code segment, one that uses a regular for loop, and one that uses a for-each loop.

A

(The data for the i-th employee is stored in an object that can be referred to as employeeData[i]. The four pieces of data about that employee are members of this object and can be referred to as:

employeeData[i].firstName
employeeData[i].lastName
employeeData[i].hourlyWage
employeeData[i].yearsWithCompany

The code segment uses a for loop to consider each employee in the array.)

for (int i=0; i < 100; i++) {
if ( employeeData[i].yearsWithCompany >= 20 )
System.out.println(employeeData[i].firstName + “ “ +
employeeData[i].lastName + “: “ +
employeeData[i].hourlyWage);
}

Using a for-each loop:

for ( Employee emp : employeeData ) {
if ( emp.yearsWithCompany >= 20 )
System.out.println(emp.firstName + “ “ +
emp.lastName + “: “ +
emp.hourlyWage);
}

76
Q

What is the purpose of the following subroutine? What is the meaning of the value that it returns, in terms of the value of its parameter?

static double[] sums( double[][] data ) {
double[] answers = new double[ data.length ];
for (int i = 0; i < data.length; i++) {
double sum = 0;
for (int j = 0; j < data[i].length; i++)
sum = sum + data[i][j];
answers[i] = sum;
}
return answers;
}

A

The purpose of this subroutine is to find the sum of the numbers in each row of the parameter array data. The answer is returned as a one-dimensional array of double. The value of answers[i] is the sum of the numbers in row number i of data.

(In the first two lines of the method, data.length is the number of rows in data. In the nested for loop, data[i].length is the number of values in the i-th row.)

77
Q

Programs written for a graphical user interface have to deal with “events.” Explain what is meant by the term event. Give at least two different examples of events, and discuss how a program might respond to those events.

A

An event is anything that can occur asynchronously, not under the control of the program, to which the program might want to respond. GUI programs are said to be “event-driven” because for the most part, such programs simply wait for events and respond to them when they occur. In many (but not all) cases, an event is the result of a user action, such as when the user clicks the mouse button, types a character, or clicks a button. The program might respond to a mouse-click on a canvas by drawing a shape, to a typed character by adding the character to an input box, or to a click on a button by clearing a drawing. More generally, a programmer can set up any desired response to an event by writing an event-handling routine for that event.

78
Q

Explain carefully what the repaint() method does.

A

The repaint() method of a component is called to notify the system that the component needs to be redrawn. It does not itself do any drawing, and does not itself call paintComponent(), but sometime shortly after you call it, the system will call the component’s paintComponent() routine. You should call repaint() for a component when you have made some change to the state of a program that requires the appearance of that component to change.

79
Q

Java has a standard class called JPanel. Discuss two ways in which JPanels can be used.

A

A JPanel can be used as a container for other components or as a drawing surface. A JPanel is a type of component. That is, it is a visible element of a GUI. By itself, a JPanel is simply a blank rectangular region on the screen. However, a JPanel is a “container”, which means that other components can be added to it and will then appear on the screen inside the JPanel. A JPanel can also be used as a drawing surface. In order to do this, it is necessary to create a subclass of JPanel and define a paintComponent() method in that subclass. An object belonging to that subclass can then be added to another panel or other container. The paintComponent() method defines how that object will draw itself on the screen.

80
Q

Java has a standard class called MouseEvent. What is the purpose of this class? What does an object of type MouseEvent do?

A

When an event occurs, the system packages information about the event into an object. That object is passed as a parameter to the event-handling routine. Different types of events are represented by different classes of objects. An object of type MouseEvent represents a mouse or mouse motion event. It contains information about the location of the mouse cursor and any modifier keys that the user is holding down. This information can be obtained by calling the instance methods of the object. For example, if evt is a MouseEvent object, then evt.getX() is the x-coordinate of the mouse cursor, and evt.isShiftDown() is a boolean value that tells you whether the user was holding down the Shift key.

81
Q

One of the main classes in Swing is the JComponent class. What is meant by a component? What are some examples?

A

A JComponent represents a visual component of the computer’s graphical user interface. A JComponent is not completely independent. It must be added to a “container,” such as a panel. Examples of JComponents are JButtons, JTextFields, and JPanels.

82
Q

What is the function of a LayoutManager in Java?

A

A LayoutManager implements some policy for laying out all the visual components that have been added to a container, such as a JPanel. That is, it sets the sizes and positions of the components. Different types of layout managers have different rules about how components are to be arranged. Some standard layout manager classes are BorderLayout and GridLayout.

83
Q

Consider the illustration of nested panels from the beginning of Section 6.6. What type of layout manager is being used for each of the three panels in that picture?

A

The outer panel, shown in pink, seems to be using a GridLayout with two rows and one column. A GridLayout is most likely since the two components in the main panel – the other two panels, shown in light cyan – are exactly the same size. Similarly, the bottom subpanel seems to be using a GridLayout with one row and three columns. The top subpanel could be using a BorderLayout. The components on the left and right ends of the subpanel would be in the WEST and EAST positions of the BorderLayout. Each of these components would then be shown at its own preferred width, which would explain how their widths could be different. The third component, in the center of the subpanel, would then be in the CENTER position.

84
Q

Explain how Timers are used to do animation.

A

Displaying an animation requires showing a sequence of frames. The frames are shown one after the other, with a short delay between each frame and the next. A Timer can generate a sequence of ActionEvents. When a timer is used to do animation, each event triggers the display of another frame. The ActionListener that processes events from the timer just needs to be programmed to display a new frame each time its actionPerformed() method is called. Usually, the actionPerformed() method just changes the values of some state variables and calls repaint() to make the effect of the changes visible on the screen.

85
Q

What is a JCheckBox and how is it used?

A

A JCheckBox is a component that has two possible states, “selected” and “not selected”. The user can change the state by clicking on the JCheckBox. If box is a variable of type JCheckBox, then a program can set the state of the box to “selected” by calling box.setSelected(true) and can unselect the box by calling box.setSelected(false). The current state can be determined by calling box.isSelected(), which is a boolean-valued function. A JCheckBox generates an event of type ActionEvent when it changes state. A program can listen for these events if it wants to take some action at the time the state changes. Often, however, it’s enough for a program simply to look at the state of the JCheckBox when it needs it.

86
Q

How is the preferred size of a component set, and how is it used?

A

Standard components such as JButton and JLabel are responsible for computing their own preferred size, and the preferred size of a container is usually computed by the layout manager for that container, but it is possible to set the preferred size of a component, comp, by calling the method comp.setPreferredSize(dim), where dim is an object of type Dimension. When a JPanel is used as a drawing surface, it is usually necessary to set its preferred size in this way, since otherwise its preferred size will be zero.

A layout uses the preferred sizes of all the components in a container when it decides how to lay out those components. It also uses the components’ preferred sizes when computing the preferred size of the container. (Note that the preferred size is only preferred; it is not necessarily the size at which the component will appear on screen. The actual size can depend on which layout manager is used, the position of the component in the layout, the size of the container, and the preferred sizes of other components in the container.)