Chapter 3 Using Classes and Objects Flashcards

1
Q

What is a null reference?

A

A null reference is a reference that does not refer to any object. The reserved word null can be used to check for null references before following them.

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

What does the new operator accomplish?

A

The new operator creates a new instance (an object) of the specified class. The constructor of the class is then invoked to help set up the newly created object.

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

Write a declaration for a String variable called author, and initialize it to the string “Fred Brooks”. Draw a graphic representation of the variable and its value.

A

The following declaration creates a String variable called author and initializes it:

String author = new String(“Fred Brooks”);

For strings, this declaration could have been abbreviated as follows:

String author = “Fred Brooks”;

This object reference variable and its value can be depicted as follows:

author || –||—–>||”Fred Brooks”||

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

Write a code statement that sets the value of an integer variable called size to the length of a String object called name.

A

To set an integer variable size to the length of a String object called name, you code:

 size = name.length();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an alias? How does it relate to garbage collection?

A

Two references are aliases of each other if they refer to the same object. Changing the state of the object through one reference changes it for the other because there is actually only one object. An object is marked for garbage collection only when there are no valid references to it.

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

Assume s1, s2, and s3 are String variables initialized to “Amanda”, “Bobby”, and “Chris”, respectively. Which String variable or variables are changed by each of the following statements?

a. System.out.println(s1);
b. s1 = s3.toLowerCase();
c. System.out.println(s2.replace(‘B’, ‘M’));
d. s3 = s2.concat(s1);

A

Strings are immutable. The only way to change the value of a String variable is to reassign it a new object. Therefore, the variables changed by the statements are: a. none, b. s1, c. none, d. s3

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

What output is produced by the following code fragment?

String s1 = "Foundations";
String s2;
System.out.println(s1.charAt(1));
s2 = s1.substring(0, 5);
System.out.println(s2);
System.out.println(s1.length());
System.out.println(s2.length());
A

The output produced is:

o
Found
11
5

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

Write a statement that prints the value of a String object called title in all uppercase letters.

A

The following statement prints the value of a String object in all uppercase letters:

System.out.println(title.toUpperCase());

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

Write a declaration for a String variable called front, and initialize it to the first 10 characters of another String object called description.

A

The following declaration creates a String object and sets it equal to the first 10 characters of the String description;

String front = description.substring(0, 10);

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

What is a Java package?

A

A Java package is a collection of related classes. The Java standard class library is a group of packages that support common programming tasks.

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

What does the java.net package contain? The javax.swing package?

A

Each package contains a set of classes that support particular programming activities. The classes in the java.net package support network communication and the classes in the javax.swing class support the development of graphical user interfaces.

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

What package contains the Scanner class? The String class? The Random class? The Math class?

A

The Scanner class and the Random class are part of the java.util package. The String and Math classes are part of the java.lang package.

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

Using the online Java API documentation, describe the Point class.

A

The Point class, according to the online Java API documentation, represents a location with coordinates (x, y) in two-dimensional space.

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

What does an import statement accomplish?

A

An import statement establishes the fact that a program uses a particular class, specifying what package that class is a part of. This allows the programmer to use the class name (such as Random) without having to fully qualify the reference (such as java.util.Random) every time.

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

Why doesn’t the String class have to be specifically imported into our programs?

A

The String class is part of the java.lang package, which is automatically imported into any Java program. Therefore, no separate import declaration is needed.

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

Given a Random object called rand, what does the call rand.nextInt() return?

A

A call to the nextInt method of a Random object returns a random integer in the range of all possible int values, both positive and negative.

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

Given a Random object called rand, what does the call

rand.nextInt(20) return?

A

Passing a positive integer parameter x to the nextInt method of a Random object returns a random number in the range of 0 to x−1. So a call to nextInt(20) will return a random number in the range 0 to 19,
inclusive.

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

Assuming that a Random object has been created called generator, what is the range of the result of each of the following expressions?

a. generator.nextInt(50)
b. generator.nextInt(5) + 10
c. generator.nextInt(10) + 5
d. generator.nextInt(50) – 25

A

The ranges of the expressions are:

a. From 0 to 49
b. From 10 to 14
c. From 5 to 14
d. From -25 to 24

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

Assuming that a Random object has been created called generator, write expressions that generate each of the following ranges of integers, including the endpoints. Use the version of the nextInt method
that accepts a single integer parameter.

a. 0 to 30
b. 10 to 19
c. −5 to 5

A

The expressions to generate the given ranges are:

a. generator.nextInt(31); // range is 0 to 30
b. generator.nextInt(10) + 10; // range is 10 to 19
c. generator.nextInt(11) - 5; // range is -5 to 5

20
Q

What is a class method (also called a static method)?

A

A class or static method can be invoked through the name of the class that contains it, such as Math.abs. If a method is not static, it can be executed only through an instance (an object) of the class.

21
Q

What is the value of each of the following expressions?

a. Math.abs(10) + Math.abs(-10)
b. Math.pow(2, 4)
c. Math.pow(4, 2)
d. Math.pow(3, 5)
e. Math.pow(5, 3)
f. Math.sqrt(16)

A

The values of the expressions are:

a. 20
b. 16.0
c. 16.0
d. 243.0
e. 125.0
f. 4.0

22
Q

Write a statement that prints the sine of an angle measuring 1.23 radians

A

The following statement prints the sine of an angle measuring 1.23 radians:

System.out.println(Math.sin(1.23));

23
Q

Write a declaration for a double variable called result and initialize it to 5 raised to the power 2.5.

A

The following declaration creates a double variable and initializes it to 5 raised to the power 2.5:

double result = Math.pow(5, 2.5);

24
Q

Using the online Java API documentation, list three methods of the Math class that are not included in Figure 3.5.

A

Examples of methods that are not listed in Figure 3.5 include:

static int min(int a, int b)
static float max(long a, long b)
static long round(double a)

25
Q

Describe how you request a NumberFormat object for use within a program.

A

To obtain a NumberFormat object for use within a program, you request an object using one of the static methods provided by the NumberFormat class. The method you invoke depends upon your intended use of the object. For example, if you intend to use it for formatting percentages, you might code:
NumberFormat fmt = NumberFormat.getPercentInstance();

26
Q

Suppose that in your program you have a double variable named cost. You want to output the value stored in cost formatted as the currency of the current locale.

a. Write a code statement that declares and requests a
NumberFormat
object named moneyFormat that can be used to
represent currency in the format of the current locale.
b. Write a code statement that uses the moneyFormat
object and prints the value of cost, formatted as the
currency of the current locale.
c. What would be the output from the statement you
wrote in part
(b) if the value in cost is 54.89 and your computer’s
locale is set to the United States? What if your
computer’s locale is set to the United Kingdom?

A

a. The statement is:
NumberFormat moneyFormat =
NumberFormat.getCurrencyInstance();

Do not forget, you also must import 
java.text.NumberFormat into your program. b. The statement is:
System.out.println(moneyFormat.format(cost)); c. If the locale is the United States, the output will be $54.89. 
If the locale is the United Kingdom, the output will be 
 £54.89
27
Q

What are the steps to output a floating point value as a percentage using Java’s formatting classes?

A

To output a floating point value as a percentage, you first obtain a NumberFormat object using a call to the static method getPercentageInstance of the NumberFormat class. Then, you pass the value to be formatted to the format method of the formatter object, which returns
a properly formatted string. For example:

NumberFormat fmt = NumberFormat.getPercentageInstance();
System.out.println(fmt.format(value));

28
Q

Write code statements that prompt for and read in a double value from the user, and then print the result of taking the square root of the absolute value of the input value. Output the result to two decimal places.

A

The following code will prompt for and read in a double value from the user and then print the result of taking the square root of the absolute value of the input value to two decimal places:

Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("0.00");
double value, result;
System.out.print("Enter a double value: ");
value = scan.nextDouble();
result = Math.sqrt(Math.abs(value));
System.out.println(fmt.format(result));
29
Q

Write the declaration of an enumerated type that represents movie ratings

A

The following is a declaration of an enumerated type for movie ratings:

enum Ratings {G, PG, PG13, R, NC17}

30
Q

Suppose that an enumerated type called CardSuit has been defined as follows:

enum CardSuit {clubs, diamonds, hearts, spades}

What is the output of the following code sequence?

CardSuit card1, card2;
card1 = CardSuit.clubs;
card2 = CardSuit.hearts;
System.out.println(card1);
System.out.println(card2.name());
System.out.println(card1.ordinal());
System.out.println(card2.ordinal());
A

Under the listed assumptions, the output is:

clubs
hearts
02

31
Q

Why use an enumerated type such as CardSuit defined in the previous question? Why not just use String variables and assign them values such as “hearts”?

A

By using an enumerated type, you guarantee that variables of that type will only take on the enumerated values.

32
Q

How can we represent a primitive value as an object?

A

A wrapper class is defined in the Java standard class library for each primitive type. In situations where objects are called for, an object created from a wrapper class may suffice.

33
Q

What wrapper classes correspond to each of the following primitive types: byte, int, double, char, and boolean?

A

The corresponding wrapper classes are Byte, Integer, Double, Character, and Boolean.

34
Q

Suppose that an int variable named number has been declared and initialized and an Integer variable named holdNumber has been declared. Show two approaches in Java for having holdNumber represent the value stored in number.

A

One approach is to use the constructor of Integer, as follows:

holdNumber = new Integer(number);

Another approach is to take advantage of autoboxing, as follows:

holdNumber = number;

35
Q

Write a statement that prints out the largest possible int value.

A
The following statement uses the MAX_VALUE constant of the Integer class to print the largest possible int value:
	 System.out.println(Integer.MAX_VALUE);
36
Q

What is the difference between a frame and a panel?

A

Both a frame and a panel are containers that can hold GUI elements. However, a frame is displayed as a separate window with a title bar, whereas a panel cannot be displayed on its own. A panel is often displayed inside a frame.

37
Q

Select the term from the following list that best matches each of the following phrases:

container, content pane, frame, heavyweight, label, layout manager, lightweight, panel

a. A component that is used to hold and organize other
components.
b. A container displayed in its own window with a title
bar.
c. Its primary role is to help organize other components
in a GUI; it must be added to another container to be
displayed.
d. This type of component is managed by the
underlying operating system.
e. This type of component is managed by the Java
program itself.
f. The part of a frame that displays visible elements.
g. A component that displays a line of text in a GUI.
h. Determines how the components in a container are
arranged on the screen.

A

The term that best matches is

a. container
b. frame
c. panel
d. heavyweight
e. lightweight
f. content pane
g. label
h. layout manager

38
Q

Run the Authority program. Describe what happens if you resize the frame by dragging the bottom-right corner towards the right. Explain.

A

If you resize the frame by dragging the bottom right corner toward the right, the saying changes from being spread across two lines to being on one line. This happens because no special instructions were included to describe the layout of the container, in which case components of a panel arrange themselves next to each other if the size of the panel allows.

39
Q

Which of the following statements best describes how the GUI of the Authority program is constructed?

■ A frame is added to a panel, which is added to
two labels.
■ Labels are added to a panel, which is added to
the content pane of
a frame.
■ Frames, panels, and labels are added to the
foreground.
■ A panel displays two labels to the user.

A

The best description is “Labels are added to a panel, which is added to a content pane of a frame.”

40
Q

What is the result of separately making each of the following changes to the Authority program? You may make the change, compile and run the program, and observe and report the results. Briefly explain what you observe.

a. The dimensions passed to the setPreferredSize
method are (300, 300) instead of (250, 75).
b. The background color is set to black instead of
yellow.
c. The order of the two label instantiation statements is
reversed (i.e., first you create label2 as a new JLabel,
passing it the string “but raise your hand first.”, and
then you create label1 as a new JLabel, passing it the
string “Question authority,”).
d. The order of the two primary add statements is
reversed (i.e., first you add label2 to the primary
panel, and then you add label1).

A

The results of the changes are
a. Due to the new dimensions the panel is larger and square.
b. The saying is not visible. You just see a black panel because the
saying, which is written in black, blends in with the background.
c. There is no change.
d. Since the labels are added in the opposite order, the saying is “backwards”—that is, it reads “but raise your hand first.” followed by
“Question authority.”

41
Q

What is the containment hierarchy of a Java graphical user interface?

A

The containment hierarchy of a graphical user interface identifies the nesting of elements within the GUI. For example, in a particular GUI, suppose some labels and buttons are contained within a panel that is
contained within another panel that is contained within a frame. The containment hierarchy can be represented as a tree that indicates how all the elements of a GUI are nested within each other.

42
Q

In the NestedPanels program, how many panels are created? What are the names of the panel variables?

A

In the NestedPanels program, there are three panels created: subPanel1, subPanel2, and primary.

43
Q

In the NestedPanels program, which panels are added to another panel? Which panel are they added to? Which panel is explicitly added to the content pane of the frame?

A

In the NestedPanels program, subPanel1 and subPanel2 are added to the primary panel. The primary panel is explicitly added to the content pane of the frame.

44
Q

How many frames, panels, image icons, and labels are declared in the LabelDemo program?

A

One frame, one panel, one image icon, and three labels are declared in the LabelDemo program

45
Q

Consider one of the label instantiation statements from the LabelDemo program:

label12 = new JLabel(“Devil Right”, icon, SwingConstants.CENTER);

Explain the role of each of the three parameters passed to the JLabel constructor.

A

In the label instantiation statement from the LabelDemo program:

label2 = new JLabel(“Devil Right”, icon, SwingConstants.CENTER);

the first parameter defines the text, the second parameter provides the image, and the third parameter indicates the horizontal alignment of the label.

46
Q

What is the result of separately making each of the following changes to the LabelDemo program? You may make the change, compile and run the program, and observe and report the results. Briefly explain
what you observe.

a. Change the third parameter of each of the three
JLabel constructor calls to SwingConstants.LEFT.
b. Change the horizontal text position of label2 from
LEFT to RIGHT.
c. Change the horizontal text position of label2 from
LEFT to BOTTOM.
d. Change the vertical text position of label3 from
BOTTOM to CENTER

A

The results of the changes are:
a. Changing the horizontal alignment of the labels has
no visua effect. The horizontal alignment describes
only how text and icons are aligned within a label.
Since a label’s area is typically exactly the size
needed to display the label, label alignment within that
area is irrelevant.
b. The change in the text position results in the text “Devil Right”
appearing to the right of the second image, instead of to its left
c. The change in the text position results in a run-time error—
“Bottom” is not a valid argument for the setHorizontalTextPosition method.
d. Since you changed the vertical position of the text within the label,
the text “Devil Above” appears directly on the third image