Java Programming 8th Edition Joyce Farrell- Test Bank

Page 1

Java Programming 8th Edition Joyce Farrell- Test Bank To purchase this Test Bank with answers, click the link below https://examquizes.com/product/java-programming-8th-edition-joyce-farrell-test-bank/

Description Java Programming 8th Edition Joyce Farrell- Test Bank Sample Questions Instant Download With Answers Chapter_03_Using_Methods_Classes_and_Objects

True / False

1. Any class can contain an unlimited number of methods. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

2. The interface is the part of a method that the method’s client does not see. a.

True

b.

False


ANSWER: POINTS: REFERENCES:

3. Application classes frequently instantiate objects that use the objects of other classes. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

4. You can identify a class that is an application because it contains a public static void main() method. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

5. You can write your own constructor methods; but when you don’t write a constructor method for a class object, Java writes one for you.


a.

True

b.

False

ANSWER: POINTS: REFERENCES:

6. A method body provides information about how other methods can interact with it. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

7. An application’s main() method must have a void return type. a.

True

b.

False

ANSWER: POINTS: REFERENCES:


8. A method’s identifier must be more than one word, must have embedded spaces, and can be a Java keyword. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

9. Parentheses in a method declaration contain parameters that are “dropped into” the method. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

10. When a value is returned from a method, you are required to use the value when the method is called. a.

True

b.

False

ANSWER:


POINTS: REFERENCES:

Multiple Choice

11. A(n) ____ is a program module that contains a series of statements that carry out a task. a.

argument

b.

c.

application

d.

ANSWER: POINTS: REFERENCES:

12. A method header is also called a(n) _____. a.

argument

b.

c.

statement

d.

ANSWER: POINTS: REFERENCES:

13. The ____ method executes first in an application, regardless of where you


physically place it within its class. a.

start()

b.

c.

main()

d.

ANSWER: POINTS: REFERENCES:

14. Data items you use in a call to a method are called ____. a.

arguments

c.

method declarations

ANSWER: POINTS: REFERENCES:

15. ____ is a principle of object-oriented programming that describes the encapsulation of method details within a class. a.

An interface

c.

Implementation hiding

ANSWER: POINTS:


REFERENCES:

16. A(n) ____ variable is known only within the boundaries of the method. a.

method

b.

c.

double

d.

ANSWER: POINTS: REFERENCES:

17. When a variable ceases to exist at the end of a method, programmers say the variable ____. a.

is undeclared

b.

c.

goes out of scope

d.

ANSWER: POINTS: REFERENCES:

18. The arguments in a method call are often referred to as ____. a.

constants

b.

c.

actual parameters

d.


ANSWER: POINTS: REFERENCES:

19. A(n) ____ causes a value to be sent from a called method back to the calling method. a.

return statement

b.

c.

instantiation

d.

ANSWER: POINTS: REFERENCES:

20. Every object is a _____ of a more general class. a.

constant

c.

method

ANSWER: POINTS: REFERENCES:

21. Method names that begin with ____ and set are very typical. a.

next


c.

read

ANSWER: POINTS: REFERENCES:

22. Public classes are accessible by all objects, which means that public classes can be ____, or used as a basis for any other class. a.

saved

b.

c.

copied

d.

ANSWER: POINTS: REFERENCES:

23. Assigning ____ to a field means that no other classes can access the field’s values. a.

user rights

b.

c.

key access

d.

ANSWER: POINTS: REFERENCES:


24. Methods used with object instantiations are called ____ methods. a.

accessor

c.

static

ANSWER: POINTS: REFERENCES:

25. Methods that retrieve values are called ____ methods. a.

static

b.

c.

class

d.

ANSWER: POINTS: REFERENCES:

26. A(n) ____ method is a method that creates and initializes class objects. a.

constructor

c.

non-static

ANSWER: POINTS: REFERENCES:


27. A unique identifier is most likely used as a ____ key in a database. a.

special

b.

c.

static

d.

ANSWER: POINTS: REFERENCES:

28. For ease in locating class methods, many programmers store them in ____ order. a.

chronological

c.

alphabetical

ANSWER: POINTS: REFERENCES:

29. A(n) ____ constructor is one that requires no arguments. a.

class

c.

explicit

ANSWER: POINTS:


REFERENCES:

30. The name of the ____ is always the same as the name of the class whose objects it constructs. a.

method

b.

c.

argument

d.

ANSWER: POINTS: REFERENCES:

31. After an object has been instantiated, its methods can be accessed using the object’s _____, a dot, and a method call. a.

identifier

c.

operator

ANSWER: POINTS: REFERENCES:

32. When an application is run, the method that must be executed first must be named ____. a.

first()

c.

main()


ANSWER: POINTS: REFERENCES:

33. ____ parameters are variables in a method declaration that accept the values from the actual parameters. a.

System

b.

c.

Public

d.

ANSWER: POINTS: REFERENCES:

34. In order to allocate the needed memory for an object, you must use the ____ operator. a.

new

b.

c.

type

d.

ANSWER: POINTS: REFERENCES:


35. Which of the following is NOT an initial value assigned to an object’s data field by a default constructor? a.

numeric fields set to 0

c.

character fields set to Unicode ‘\u0000’

ANSWER: POINTS: REFERENCES:

Completion

36. To execute a method, you ____________________ it from another method. ANSWER:

POINTS: REFERENCES:

37. Access specifiers are sometimes called access ____________________. ANSWER: POINTS: REFERENCES:

38. Often, programmers list the ____________________ first because it is the first method used when an object is created.


ANSWER: POINTS: REFERENCES:

39. A(n) ____________________ data type is a type whose implementation is hidden and accessed through its public methods. ANSWER: POINTS: REFERENCES:

40. Normally, you declare constructors to be ____________________ so that other classes can instantiate objects that belong to the class. ANSWER: POINTS: REFERENCES:

Matching

Match each term with the correct statement below. a.

return statement

b.

header

c.

instance variables

d.

method’s signature


e.

formal parameters

f.

static method

g.

data fields

h.

parameter type

i.

class user

REFERENCES:

41. The first line of a method ANSWER: POINTS:

42. The combination of the method name and the number, types, and order of arguments ANSWER: POINTS:

43. Included within the method declaration parentheses ANSWER: POINTS:


44. Are called class methods ANSWER: POINTS:

45. Variables in the method declaration that accept the values from the actual parameters ANSWER: POINTS:

46. Used to return a value back to the calling method ANSWER: POINTS:

47. Data components of a class ANSWER: POINTS:

48. An application or a class that instantiates objects of another prewritten class ANSWER: POINTS:

49. Variables you declare within a class, but outside of any method


ANSWER: POINTS:

Subjective Short Answer

50. What is a method and how is one used? ANSWER:

A method is a program module that contains a series of statements that carry out a method; the calling method makes a method call, which invokes the called method. each method can be called an unlimited number of times.

POINTS:

1

REFERENCE S:

120

51. What are the four components of a method header? ANSWER:

Optional access specifiers A return type An identifier Parentheses

POINTS:

1

REFERENCES:

123

52. How does the order in which methods appear in a class affect how the application executes? Please explain. ANSWER:

The order in which methods appear in a class has no bearing on the order in which t the main() method is always executed first in any Java application, and it might call order in which you call methods, not their physical placement, is what makes a diffe


POINTS:

1

REFERENCE S:

121

53. What are the two parts of every method? Describe them. ANSWER:

A method header—A method’s header provides information about how other method declaration. A method body between a pair of curly braces—The method body contains the is called its implementation. Technically, a method is not required to contain any sta create an empty method in a class. Sometimes, while developing a program, the pro the implementation later. An empty method is called a stub.

POINTS:

1

REFERENCE S:

123

54. Describe how you can use multiple arguments in a method. Provide an example. ANSWER:

You can pass multiple arguments to a method by listing the arguments within the ca values are passed to the method in a statement such as the following, the first value second value passed is referenced as rate: predictRaiseUsingRate(mySalary, promisedRate); Arguments to a method must be passed in the correct order.

POINTS:

1

REFERENCE S:

133

55. How do you use a value returned from a method? Provide an example. ANSWER:

If a method returns a value, then when you call the method, you normally use the re example, when you invoke the predictRaise() method, you might want to assign the variable named myNewSalary, as in the following statement:


myNewSalary = predictRaise(mySalary);

The predictRaise() method returns a double, so it is appropriate to assign the metho

POINTS:

1

REFERENCE S:

137

56. Describe instantiation and how it relates to ‘is-a relationships.’ ANSWER:

Everything is an object, and every object is a member of a more general class. Your pet fish is a member of the class that contains all fish. These statements represent i concrete example of the class. The difference between a class and an object parallel instantiation of a class, or one tangible example of a class.

POINTS:

1

REFERENCE S:

142-143

57. Does a programmer need to write every class he or she uses? Why or why not? ANSWER:

The same programmer does not need to write every class he or she uses. Often, you example, many programs you have seen so far in this book have used the System were provided for you by Java’s creators. Similarly, you might create a class that oth

POINTS:

1

REFERENCE S:

144

58. Describe what a public access class is and when you would use one. ANSWER:

The most liberal form of access is public. The keyword public is a class modifier. also can be extended, or used as a basis for any other class. Making access public m you want to develop two classes that are more specific, SalariedEmployee and Hour


POINTS:

1

REFERENCE S:

145

59. How do you create an object that is an instance of a class? Provide an example. ANSWER:

A two-step process creates an object that is an instance of a class. First, you supply and then you allocate computer memory for that object. For example, you might defi Employee as follows: Employee someEmployee;. In this statement, someEmployee c lowercase letter.

POINTS:

1

REFERENCE S:

154

60. What is the difference between a mutator method and an accessor method? Provide an example of each. ANSWER:

Methods that set or change field values are called mutator methods; methods that re methods conventionally start with the prefix set, and accessor methods conventiona

Mutator example: public void setEmpNum(int emp) { empNum = emp; }

Accessor example: public int getEmpNum() { return empNum;


}

POINTS:

1

REFERENCE S:

147

61. Describe fully qualified identifiers and explain why they are necessary. ANSWER:

A complete name that includes the class is a fully qualified identifier. If you want to u the method unless you use the full name. A fully qualified identifier includes the clas

POINTS:

1

REFERENCE S:

125-126

62. Explain the purpose of a return type of a method. Describe the return value of a method that returns no data. ANSWER:

A return type describes the type of data the method sends back to its calling method method that returns no data has a return type of void.

POINTS:

1

REFERENCE S:

124

63. What are the possible results if arguments to a method are passed in the wrong order? ANSWER:

If arguments to a method are passed in the wrong order, the result is one of the fol If the method can still accept both arguments, the result is a logical error; that is, t incorrect results.

If the method cannot accept the arguments, passing arguments in the wrong order


POINTS:

1

REFERENCES:

134

64. When creating a method that requires multiple parameters, why would a programmer need to understand a method’s signature, and why must a method call match the called method’s signature? ANSWER:

You can write a method so that it takes any number of parameters in any order. How method must match in order—both in number and in type—the parameters listed in combination of the method name and the number, types, and order of arguments. A

POINTS:

1

REFERENCE S:

134

65. public static void predictRaise(double salary) { double newSalary; final double RAISE_RATE = 1.10; newSalary = salary * RAISE_RATE; System.out.println(“Current salary: ” + salary + ” After raise: ” + newSalary); } In the above code, what are the parameter data type and parameter identifier? How do you identify each? ANSWER:

When you write the method declaration for a method that can receive a parameter, method, the method name, the parameter type, and a local name for the parameter salary within the parentheses indicates that the method will receive a value of type known as salary.

POINTS:

1

REFERENCE S:

132


66. In the above code, what would happen if the arguments passed to the method were passed in the wrong order? ANSWER:

Since the two methods are of the same type, there would be no syntax or compile er produce incorrect results. The newAmount value calculated would produce a result b

POINTS:

1

REFERENCE S:

133

67. Fill in the blank line in the above code to add a statement that calls a method named practiceWithCalls that passes a parameter named testing of type double. ANSWER:

The line of code to call the method would appear as follows:

practiceWithCalls(double testing);

POINTS:

1

REFERENCES:

130

68. A major advantage of a method is that it is easily reusable. What does it mean to reuse a method and what are the advantages of doing so? ANSWER:

After a method is created, you can use it in any application. You write the method on writing code and makes the code easier to manage.

POINTS:

1

REFERENCE S:

120-121

69.


Identify and describe the four components that make up the method header above. ANSWER:

1. 2. 3. 4.

Optional access specifier – can be public (most common), private, protect Return type – describes the type of data the method will send back to the An identifier – consists of one word with no embedded spaces and cannot Parentheses – may contain data to be sent to the method, but may be em

POINTS:

1

REFERENCES:

123-125

70. In the above code, the calculateBonus() method acts as a “black box.” What does this mean? ANSWER:

The predictRaise method calls the calculateBonus() method. However, you do not kn know that it accepts a double as a parameter (because newAmount is passed into it) automatically be promoted to a double. In this way, the method acts as a black box.

POINTS:

1

REFERENCE S:

129,138,142

71. Write a valid class header with public access. Assign a valid identifier of your choice. Then write the body of the class that contains one data field named myPractice with a data type of double. Be sure to include any necessary curly braces and semicolons. ANSWER:

public class PublicClass {

(identifier name may vary)

private double myPractice; }

POINTS:

1

REFERENCES:

145-146


72. public int getStudentNum() { return studentNum; }

In the above code, identify if the method is a mutator method or an accessor method. Describe how the two types of methods differ and how they are similar. ANSWER:

Methods that set or change field values are called mutator methods; methods that r values are called accessor methods. In Java, mutator methods conventionally start w

prefix set, and accessor methods conventionally start with the prefix get but it is conventional. The method in the above code is an accessor method because it retrieves studentN

POINTS:

1

REFERENCES :

147

73. public Employee() { empSalary = 300.00; } The above code shows the Employee class constructor. What is a constructor and how would this default constructor operate? ANSWER:

A constructor establishes an object. A default constructor is one that requires no arg Java compiler for any class you create whenever you do not write your own construc class is called, it establishes one Employee object with the identifier provided. The a specific initial values to an object’s data fields: Numeric fields are set to 0 (zero). Character fields are set to Unicode ‘\u0000’. Boolean fields are set to false.


Fields that are object references (for example, String fields) are set to null (or empty

In this example, a field named empSalary in the Employee object is assigned a value

POINTS:

1

REFERENCE S:

159-160

74. public class Employee { private int empNum; private double empSalary;

public void setEmpNum(int emp) { empNum = emp; } public void setEmpSalary(double sal) { empSalary = sal; } }

Given the class defined in the code above, write the Java statements that will create a new employee instance called employee15 and assign an empNum of 15 and empSalary of 500.00 to that employee instance. ANSWER:

Employee employee15;


employee15 = new Employee(); employee15.setEmpNum(15); employee15.setEmpSalary(500.00);

POINTS:

1

REFERENCES:

154-155

Chapter_05_Making_Decisions

True / False

1. You write pseudocode in everyday language, not the syntax used in a programming language. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

2. An alternative to using a Boolean expression, such as someVariable == 10, is to store the Boolean expression’s value in a Boolean variable. a.

True


b.

False

ANSWER: POINTS: REFERENCES:

3. When you create a block, you must place multiple statements within it. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

4. When you use nested if statements, you must pay careful attention to placement of any else clauses. a.

True

b.

False

ANSWER: POINTS: REFERENCES:


5. In the switch structure, break is followed by one of the possible values for the test expression and a colon. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

6. Computers contain switches that are set to on or off. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

7. When writing a statement with the two-line format, you must be sure to type a semicolon at the end of the first line in order to ensure accurate results. a.

True

b.

False

ANSWER: POINTS:


REFERENCES:

8. Although it is possible to block statements that depend on an if, you cannot likewise block statements that depend on an else. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

9. Although not required, it is common procedure to align the keyword if with the keyword else. a.

True

b.

False

ANSWER: POINTS: REFERENCES:

10. You use the NOT operator, which is written as the exclamation point (!), to negate the result of any Boolean expression. a.

True

b.

False


ANSWER: POINTS: REFERENCES:

Multiple Choice

11. A ____ consists of written steps in diagram form, as a series of shapes connected by arrows. a.

pseudocode chart

c.

sequence structure

ANSWER: POINTS: REFERENCES:

12. A logical structure called a(n) ____ structure is when one step follows another unconditionally. a.

straight

b.

c.

sequence

d.

ANSWER: POINTS:


REFERENCES:

13. The simplest statement you can use to make a decision is the ____ statement. a.

this

c.

true false

ANSWER: POINTS: REFERENCES:

14. When an expression containing a ____ is part of an if statement, the assignment is illegal. a.

single equal sign

c.

double equal sign

ANSWER: POINTS: REFERENCES:

15. A(n) ____ statement is the decision structure you use when you need to take one or the other of two possible courses of action. a.

Boolean

c.

single-alternative if


ANSWER: POINTS: REFERENCES:

16. When you execute an if…else statement, only one of the resulting actions takes place depending on the evaluation of the ____ following the if. a.

Boolean expression

b.

c.

else statement

d.

ANSWER: POINTS: REFERENCES:

17. When you place a block within an if statement, it is crucial to place the ____ correctly. a.

periods

b.

c.

commas

d.

ANSWER: POINTS: REFERENCES:


18. Just as you can block statements that depend on an if, you can also block statements that depend on a(n) ____. a.

Boolean expression

c.

constant

ANSWER: POINTS: REFERENCES:

19. When you block statements, you must remember that any ____ you declare within a block is local to that block. a.

method

b.

c.

variable

d.

ANSWER: POINTS: REFERENCES:

20. Statements in which an if structure is contained inside another if structure are commonly called ____ if statements. a.

nested

c.

blocked

ANSWER:


POINTS: REFERENCES:

21. The compiler does not take indentation into account when compiling code, but consistent indentation can help readers understand a program’s ____. a.

machine language

c.

decision

ANSWER: POINTS: REFERENCES:

22. The AND operator is written as two ____. a.

plus signs

c.

ampersands

ANSWER: POINTS: REFERENCES:

23. When you use the && operator, you must include a complete _____ on each side. a.

mathematical expression

c.

variable


ANSWER: POINTS: REFERENCES:

24. You can use the ____, which is written as ||, if you want some action to occur when at least one of two conditions is true. a.

conditional OR operator

c.

range check

ANSWER: POINTS: REFERENCES:

25. A(n) ____ is a series of if statements that determine whether a value falls within a specified range. a.

scope check

b.

c.

range test

d.

ANSWER: POINTS: REFERENCES:


26. The ____ statement is useful when you need to test a single variable against a series of exact integer, character, or string values. a.

switch

c.

else

ANSWER: POINTS: REFERENCES:

27. You can leave out the ____ statements in a switch structure. a.

break

b.

c.

if

d.

ANSWER: POINTS: REFERENCES:

28. The ____ requires three expressions separated with a question mark and a colon. a.

flowchart

b.

c.

sequence structure

d.

ANSWER: POINTS:


REFERENCES:

29. The ____ operator is written as the exclamation point ( ! ). a.

equality

c.

assignment

ANSWER: POINTS: REFERENCES:

30. The ____ operator is always evaluated before the OR operator. a.

Assignment

c.

Conditional

ANSWER: POINTS: REFERENCES:

31. When working with logical operators, you can always use ____ to change precedence. a.

conditional operators

c.

parentheses


ANSWER: POINTS: REFERENCES:

32. A ____ checks a value, and based on the result performs one of two actions. a.

short-circuit structure

c.

decision structure

ANSWER: POINTS: REFERENCES:

33. Using the flowchart above, which decision statement will correctly check that hoursWorked is greater than or equal to the FULL_WEEK constant? a.

hoursWorked == FULL_WEEK

c.

hoursWorked >= FULL_WEEK

ANSWER: POINTS: REFERENCES:

34. if (quotaAmt > 100 || sales > 100 && productCode == “C”)


bonusAmt = 50;

When the above code is executed, which operator is evaluated first?

a.

&&

c.

||

ANSWER: POINTS: REFERENCES:

35. When using equals and not equals for comparisons with objects, you compare the objects’ ____ instead of actual values. a.

reference fields

b.

c.

Boolean values

d.

ANSWER: POINTS: REFERENCES:

Completion

36. ____________________ is a tool that helps programmers plan a program’s logic by


writing plain English statements. ANSWER: POINTS: REFERENCES:

37. A(n) ____________________ structure is one that involves choosing between alternative courses of action based on some value within a program. ANSWER: POINTS: REFERENCES:

38. ____________________ statements are particularly useful when two conditions must be met before some action is taken. ANSWER: POINTS: REFERENCES:

39. Both & and | are valid Java operators, but a single & or | with integer operands operate on individual ____________________ rather than making comparisons in logical conditions as && and || do. ANSWER: POINTS: REFERENCES:

40. You are never required to use a switch structure; you can always achieve the same results with nested ____________________ statements.


ANSWER: POINTS: REFERENCES:

Matching

Match each term with the correct statement below. a.

relational operator

b.

conditional operator

c.

Boolean values

d.

equality

e.

switch statement

f.

pipes

g.

dual-alternative

h.

!

i.

logical AND operator

REFERENCES:


41. true and false ANSWER: POINTS:

42. A double equal sign ANSWER: POINTS:

43. Two possible courses of action ANSWER: POINTS:

44. Two ampersands ANSWER: POINTS:

45. Used in the OR operator ANSWER: POINTS:

46. > or < ANSWER: POINTS:


47. An alternative to using a series of nested if statements ANSWER: POINTS:

48. Separated with a question mark and a colon ANSWER: POINTS:

49. The logical NOT operator ANSWER: POINTS:

Subjective Short Answer

50. Why do programmers use pseudocode? ANSWER:

When computer programmers write programs, they rarely just sit down at a keyboar portions of programs using paper and pencil. Programmers often use pseudocode, a English statements. Using pseudocode requires that you write down the steps neede language, not the syntax used in a programming language.

POINTS:

1

REFERENCE S:

246

51. Describe how a sequence structure works.


ANSWER:

In a sequence structure, one step follows another unconditionally. A sequence struct another with no chance to branch away or skip a step.

POINTS:

1

REFERENCE S:

246

52. An alternative to using a Boolean expression, such as quizScore == 10, is to store the Boolean expression’s value in a Boolean variable. How could you express this in Java? ANSWER:

For example, if isPerfectScore is a Boolean variable, then the following statement isPerfectScore: isPerfectScore = (quizScore == 10); Then, you can write the if as: if(isPerfectScore) System.out.println(“The score is perfect”);

POINTS:

1

REFERENCES:

250

53. Why would a programmer execute more than one statement that depends on the evaluation of a Boolean expression, and how could he or she do it in Java? ANSWER:

Often, you want to take more than one action following the evaluation of a Boolean e to display several separate lines of output or perform several mathematical calculati evaluation of a Boolean expression, you use a pair of curly braces to place the depen

POINTS:

1

REFERENCE S:

254


54. Within an if or an else statement, how can you code as many dependent if statements as you need and why is this useful? ANSWER:

Within an if or an else clause, you can code as many dependent statements as you which a decision is contained inside either the if or else clause of another decision a useful when two or more conditions must be met before some action is taken.

POINTS:

1

REFERENCE S:

260

55. Why would a programmer use an && operator when using nested if statements? ANSWER:

You are never required to use the && operator because using nested if statements a makes your code more concise, less error-prone, and easier to understand.

POINTS:

1

REFERENCE S:

265

56. What is a range check? Provide an example of a range check using a series of if..else statements using the values defined below.

final final final final final

double double double double double

ANSWER:

HIGH_LIM = 1000.00; HIGH_RATE = 0.08; MED_LIM = 500.00; MED_RATE = 0.06; LOW_RATE = 0.05;

A range check is a series of statements that determine to which of several con

if(saleAmount >= HIGH_LIM) commissionRate = HIGH_RATE; else if(saleAmount >= MED_LIM) commissionRate = MED_RATE;


else commissionRate = LOW_RATE;

Or, perhaps somewhat more efficient:

if(saleAmount < LOW_LIM) commissionRate = LOW_RATE; else if(saleAmount < MED_LIM) commissionRate = MED_RATE; else commissionRate = HIGH_RATE;

POINTS:

1

REFERENCES:

270, 272

57. What is wrong with the following statement? How could you correct it? if(payRate < 5.85 && payRate > 60) System.out.println(“Error in pay rate”); ANSWER:

As a single variable, no payRate value can ever be both below 5.85 and over 60 at th execute, no matter what value the payRate has. In this case, you must write the follo circumstances: if(payRate < 5.85 || payRate > 60) System.out.println(“Error in pay rate”);

POINTS:

1

REFERENCE S:

273

58. List and explain the keywords used with the switch statement. ANSWER:

switch starts the statement and is followed immediately by a test expressio case is followed by one of the possible values for the test expression and a


break optionally terminates a switch structure at the end of each case.

default is optionally used prior to any action that should occur if the test var

POINTS:

1

REFERENCES:

275

59. What is a conditional operator? Show an example of an expression that uses a conditional operator. ANSWER: The conditional operator requires three expressions separated with a question statement.

testExpression ? trueResult : falseResult;

The first expression, testExpression, is a Boolean expression that is evaluated as tru the value of the expression following the question mark (trueResult). If the value of t value of falseResult.

POINTS:

1

REFERENCE S:

280

60. Explain the use of the NOT operator. ANSWER:

You use the NOT operator, which is written as the exclamation point ( ! ), to negate t evaluates as true becomes false when preceded by the NOT operator; and according true.

POINTS:

1

REFERENCE

281


S:

61. In Boolean expressions, when you want to execute more than one statement based on the results of the expression, you place statements within a block. What is a block and why is it important in decision statements? Why are curly braces crucial when blocking an if statement? ANSWER:

To execute more than one statement that depends on the evaluation of a Boolean ex statements within a block. When you place a block within an if statement, it is crucia multiple statements must be treated as a block. When you create a block, you do no to place curly braces around a single statement. For clarity, some programmers alwa even when there is only one statement in the block.

POINTS:

1

REFERENCE S:

254-255

62. Create an if statement that will check if the variable salesAmt is greater than the constant SALES_QUOTA. If true, create a block statement that will calculate salesAmt * BONUS_PERCENT and store the result in a variable named bonusPay. The block statement will then compute totalPay by adding salesAmt to bonusPay. Outside of the if structure, add a println statement that will output the totalPay value. Be sure to use curly braces and semicolons appropriately. ANSWER:

if(salesAmt > SALES_QUOTA) { bonusPay = salesAmt * BONUS_PERCENT; totalPay = salesAmt + bonusPay; } System.out.println(“Total pay is ” + totalPay);

POINTS:

1

REFERENCES:

256-258


63. Create an if statement that checks if the variable salesAmt is greater than or equal to the QUOTA_AMT constant. Use the logical OR operator to also check if salesAmt is greater than or equal to the HIGH_SALES constant. If either expression is true, assign the value of the LARGE_QUOTA constant to the variable bonusAmt. ANSWER:

if(salesAmt >= QUOTA_AMT || salesAmt >= HIGH_SALES) bonusAmt = LARGE_QUOTA;

POINTS:

1

REFERENCES:

265

64. public class Student { private int studentNum; private int studentScore; public int MAX_NUM = 500; public int MAX_SCORE = 100; Student(int num, int score) { } Decision making can be used to control the allowed values in an object’s fields. In the above code, the Student class contains two fields that hold a student number and a score. A constructor accepts values for these fields as parameters. Write the code between the curly brackets that will determine whether the value of num is less than the MAX_NUM constant. If true, assign the value of num to studentNum. Otherwise, assign the value of MAX_NUM to the studentNum. Then check if the value of score is less than or equal to MAX_SCORE. If true, assign the value of score to studentScore. Otherwise, assign 0 to studentScore. ANSWER:

if(num <= MAX_NUM) studentNum = num; else studentNum = MAX_NUM; if(score <= MAX_SCORE) studentScore = score; else studentScore = 0;

POINTS:

1

REFERENCES:

285


65. Using the above flowchart and code, why will the above statements execute but provide unintended results? Write the statement correctly. ANSWER:

There should be no semicolon at the end of the first line of the if statement following The statement should end after the println() call, so that is where you type the semic

if(quizScore == 10) System.out.println(“The score is perfect”);

POINTS:

1

REFERENCE S:

249

66. Write a single-alternative if statement that will check if a variable named maxValue is equal to 100. If true, use a println statement to output “You have reached the limit”. ANSWER:

if (maxValue == 100) System.out.println (“You have reached the limit”); (Be sure there is no semicolon at the end of the first line.)

POINTS:

1

REFERENCES:

249

67. if (maxValue = 100) System.out.println (“Your limit has been reached”);

Why is the above if statement illegal? How would you fix it? ANSWER:

A common programming error occurs when a programmer uses a single equal sign r equivalency. The expression maxValue = 100 does not compare maxValue to 100. In the expression maxValue = 100 is used in the if statement, the assignment is illegal


Then, if statement should be written as:

if(maxValue == 100) System.out.println(“Your limit has been reached”);

POINTS:

1

REFERENCE S:

250

68. Create an if…else statement that will check if the maxValue variable is equal to 100. If true, create a println statement that will output “Max reached”. If false, create a println statement to output “Keep trying”. ANSWER:

if(maxValue == 100) System.out.println(“Max reached”); else System.out.println(“Keep trying”);

POINTS:

1

REFERENCES:

252

69. if(qtySold > QUOTA) bonusPay = 50; totalPay = regPay + bonusPay; System.out.println(“Your totalPay amount is ” + totalPay);

Why is the above code incorrect? Write the code that will provide the correct result. ANSWER:

When you place a block within an if statement, it is crucial to place the curly braces omitted. When qtySold > QUOTA is true, bonusPay is calculated and the if expression


every time the program runs, no matter what value is stored in qtySold.

if(qtySold > QUOTA) { bonusPay = 50; totalPay = regPay + bonusPay; } System.out.println(“Your totalPay amount is ” + totalPay);

POINTS:

1

REFERENCE S:

255-256

70. if(firstValue == secondValue) { int total = firstValue + secondVaue; System.out.println(“The values are equal”); } System.out.println(“The total is ” + total); Why will the above println() statement cause an error? ANSWER:

When blocking statements, it is crucial to remember that any variable declared with named total is local to the block following the if. The ending println statement cause

POINTS:

1

REFERENCE S:

258


71. Write a nested if statement that will check if the variable qtySold is greater than the QTY_QUOTA constant. If true, evaluate a second expression that will check if the variable totalSales is greater than the constant SALES_QUOTA. If the second expression is also true, create an assignment statement that will assign the constant BONUSAMT to the variable bonus. After BONUSAMT is assigned, the if structure ends. ANSWER:

if(qtySold > QTY_QUOTA) if(totalSales > SALES_QUOTA) bonus = BONUSAMT; (The semicolon will only be placed after the final statement.)

POINTS:

1

REFERENCES:

260-261

72. Using the above flowchart, write the nested if…else statements that will correctly choose among alternative courses of action based on the values of itemsSold and totalValue. ANSWER:

if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = LARGE_BONUS; else bonus = MEDIUM_BONUS; else bonus = SMALL_BONUS;

POINTS:

1

REFERENCES:

262

73. Use the above flowchart to create the code using the logical && operator to determine if a SALES_BONUS will be assigned to the variable bonus. ANSWER:


if(itemsSold > MIN_ITEMS && totalValue >= MIN_VALUE) bonus = SALES_BONUS;

POINTS:

1

REFERENCES:

264

74. Create a switch statement that will test the value of a variable named score. If score has a value of 5, create a println statement that will output “Excellent”. If score has a value of 4, create a println statement that will output “Great”. If score has a value of 3, create a println statement that will output “Good”. If score has a value of 2, create a println statement that will output “Fair”. If score has a value of 1, create a println statement that will output “Needs improvement”. If score does not contain a matching value for any of the case statements, create a println statement that will output “Retake test”. ANSWER:

switch(score) { case 5: System.out.println(“Excellent”); break; case 4: System.out.println(“Great”); break; case 3: System.out.println(“Good”); break; case 2: System.out.println(“Fair”);


break; case 1: System.out.println(“Needs improvement”); break; default: System.out.println(“Retake test”); }

POINTS:

1

REFERENCES:

275-276


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.