ap computer

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Assume you have two String variables, item1 and item2, whose contents may or may not be the same. Write a condition which evaluates to true if the string values in these two variables are not exactly the same.

!item1.equals(item2) or: !item2.equals(item1)

Write the operator used for string concatenation.

+

Assume: int a = 3, b = 2; double c = 5.0; And evaluate the expression: (c + a / b) / 8 * 2 Show each step to indicate the evaluation sequence.

(c + a / b) / 8 * 2 [] (5.0 + 3 / 2) / 8 * 2 [] (5.0 + 1) / 8 * 2 [] 6.0 / 8 * 2 [] 0.75 * 2 [] 1.5

The file extension for a file containing compiled Java code is

.class

What is the file extension for a bytecode file?

.class

The file extension for a Java source-code file is

.java

Write the prologue for a Java program called OutputDemo. List yourself as the author. Include a comment that says "This demonstrates program output."

/**************************************** * OutputDemo.java * Student Name * * This demonstrates program output. ****************************************/

What is a Boolean value?

A Boolean value is a value that may be either true or false.

Fill in the blanks: a) A method that reads one of an object's data items is called a/an ____________. b) A method that changes one of an object's data items is called a/an ____________.

Fill in the blanks: a) A method that reads one of an object's data items is called an accessor. b) A method that changes one of an object's data items is called a mutator.

What situation makes an object eligible for "garbage collection"?

An object becomes eligible for garbage collection when there are no longer any references to it.

Suppose your code has already created and fully initialized an instance called car1 of a class called Car, which defines two private instance variables, make and model. Write Java code that creates another instance called car2 that has exactly the same values for its make and model instance variables. Assume the Car class has defined accessor and mutator methods but does not have a makeCopy method capable of performing the complete copying operation in a single method call.

Car car2 = new Car(); car2.setMake(car1.getMake()); car2.setModel(car1.getModel());

Assume that a class called Cat includes a method with this header: public static int getCatCount() Write a Java statement that retrieves the current cat count and assigns it to an already-declared local variable called catCount in the main method of the CatDriver class.

Cat count retrieval: catCount = Cat.getCatCount();

What two things must you change or add to convert an ordinary mutator (set- method) into a mutator that is chainable?

Change the void in the method heading to the name of the method's class. Add the final statement: return this;

Write a Java expression that evaluates to true if and only if a character, ch, is an alphabetical lowercase letter.

Character.isLetter(ch) && Character.isLowerCase(ch)

For each class Java automatically provides a zero-parameter constructor that is always available unless you override it with an explicitly defined a zero-parameter constructor. (T / F)

False

Assuming that x, y, and z are double variables, write Java statements that implement these mathematical operations: a) z ← x y b) z ← square root of y c) z ← sin(x), where x is in degrees.

Math operations in Java: a) z = Math.pow(x, y); b) z = Math.sqrt(y); c) y = Math.toRadians(x); z = Math.sin(y); or: z = Math.sin(Math.toRadians(x)); or: z = Math.sin(x * Math.PI / 180.);

What does this statement do? import java.util.*;

It enables you to use all of the classes in the Java API util package.

define GHZ in familiar terms

It is the tick rate, event rate, or cycle rate in billions per second.

Assume you are in the main method in a MouseDriver class. a) Write a statement that creates a Mouse object to represent your personal pet mouse, whom you called "Sweetie". b) Write another statement that uses a getWeight method (defined in the Mouse class) to retrieve Sweetie's current weight, and then assign that retrieved value to a previously declared local variable called weight.

MouseDriver code: a) Mouse sweetie = new Mouse();

Given the initialization: String rachelCarson = "if, knowing, we have concluded that we are being asked" + " to take senseless and frightening risks; we should" + " look about and see what other course is open to us."; Write a Java code fragment that inserts ─ just before the semicolon inside the above text ─ the following additional text: String insert = ", then we should no longer accept the counsel of those" + " who tell us that we must fill our world with" + " poisonous chemicals";

Rachel Carson quotation insertion code: int index = rachelCarson.indexOf(";"); rachelCarson = rachelCarson.substring(0, index) + insert + rachelCarson.substring(index); or: rachelCarson = rachelCarson.replaceAll(";", insert + ";"); or: rachelCarson = rachelCarson.replaceFirst(";", insert + ";");

Assume code that has already made the declaration: boolean randomBoolean; Write a Java code fragment that makes randomBoolean be a random Boolean variable. [Hint: Use the random method in the Java API Math class to assign randomBoolean a value of either true or false, with equal probability.]

Random Boolean variable creation code: if (Math.random() >= 0.5) { randomBoolean = true; } else { randomBoolean = false; }

Assume that your code already includes the statement: import java.util.*; Write a pair of Java statements that create an instance of the Random class, and use this to generate a random number from a Gaussian distribution whose mean value is 2.5 and whose standard deviation is 0.4.

Random number generation: Random random = new Random(); System.out.println(2.5 + 0.4 * random.nextGaussian());

What company developed the Java language?

Sun (or Sun Microsystems)

In all Java API method headings, the method name is preceded by the name of a type (or the word void). What does that type name tell you?

The method's type name specifies the type of the value (if any) that the method returns.

Given the code: double interestRate = 0.05; double balance = 100.00; int interestInDollars = (int) interestRate * balance; System.out.println(interestInDollars); b) Rewrite the interestInDollars initialization statement to solve the problem.

To fix the problem, make the cast operate on the combination of both double variables, like this: int interestInDollars = (int) (interestRate * balance);

The least encapsulated type of variable is a ___________ variable.

class (or static)

What organization created the "Ten Commandments of Computer Ethics"?

computer ethics institute

Using "camelCase", write the name for a Java variable that describes a computers price

computerPrice

Convert the following pseudocode into Java code using nested for loops: x ← 2 while x <= 3 { y ← 1 while y <= 3 { print x increment y } newline increment x }

for (int x=2; x<=3; x++) { for (int y=1; y<=3; y++) { System.out.print(x); } System.out.println(); }

Assume that you are looking at a command-prompt window, and the current directory contains a source-code file for a Java program called TestProgram. What do you enter after the command prompt to compile that program?

javac TestProgram.java

CD-ROM (output, input, memory)

memory

USB flash (output, input, memory)

memory

monitor (output, input, memory)

output

printer (output, input, memory)

output

Write a pair of pseudocode statements that prompts the user for a body weight in kilograms and then inputs the entered value and assigns it to a variable called kgBodyWeight.

print "Enter body weight in kg: " input kgBodyWeight

Draw a flowchart for an algorithm that prompts a user for the diameter of a circle. Then it inputs the value the user enters. Then it uses that value to calculate the perimeter. Then it outputs the perimeters value. Use ← for assignment(s).

print "Enter circle diameter: " input diameter perimeter ← π x diameter print perimeter

An informal outline that describes what a program does is called

pseudocode

Assume you have a Car class that declares two private instance variables, make and model. Write Java code that implements a two-parameter constructor that instantiates a Car object and initializes both of its instance variables.

public Car(String make, String model) { this.make = make; this.model = model; }

Assume a Car class already has a two-parameter constructor that initializes make and model attributes. Write Java code that implements an additional constructor that has three parameters ─ two String parameters to initialize the same make and model attributes initialized by the two- parameter constructor, plus another int parameter to initialize a miles variable. Your code should utilize the two-parameter constructor to implement those operations which the two- parameter constructor is already able to perform.

public Car(String make, String model, int miles) { this(make, model); this.miles = miles; }

Suppose you want to get a Java program's text input from a text file instead of from the keyboard. b) Complete the main method header: public static void main(String[] args)________________

public static void main(String[] args) throws Exception

Suppose a CarDriver program has already created and fully initialized an instance called car1 of a class Car, which defines two private instance variables, make and model. Then suppose CarDriver creates a copy of this car with these two statements: Car car2 = new Car(); car2.copyFrom(car1); Write Java code to implement this copyFrom method.

public void copyFrom(Car car) { this.make = car.make; this.model = car.model; } // end copyFrom

Suppose a CarDriver program has already created and fully initialized an instance called car1 of a class Car, which defines two private instance variables, make and model. Then suppose CarDriver creates a copy of this car with these two statements: Car car2 = new Car(); car1.copyTo(car2); Write Java code to implement this copyTo method.

public void copyTo(Car car) { car.make = this.make; car.model = this.model; } // end copyTo

What does the following code fragment print? String name = "Johnson"; System.out.println(name.charAt(4));

s

Using set ... to ... for all assignments, write pseudocode for an algorithm that establishes the base and height of a triangle as 8 and 5, respectively. Then it computes the triangle's area. Then it outputs that area.

set base to 8 set height to 5 set triangleArea to base * height / 2 print "area = " triangleArea

Assume you have made the declarations: double speed; Scanner stdIn = new Scanner(System.in); Write a statement that causes the program to read a floating point number entered on the keyboard into the variable called speed.

speed = stdIn.nextDouble();

Assume you have defined a char variable called code, which might be assigned one of the three values: 'p', 'f', or 'i'. Write a Java switch statement that prints "pass" if code == 'p', "fail" if code == 'f', or "incomplete" if code == 'i'. If the value in code is anything else, the statement should print "data error".

switch (code) { case 'p': System.out.println("pass"); break; case 'f': System.out.println("fail"); break; case 'i': System.out.println("incomplete"); break; default: System.out.println("data error"); }

All primitive type names begin with a lowercase letter, and it's the convention to begin all reference type names with an uppercase letter. (T / F)

true

Identifiers must consist entirely of letters, digits, dollar signs, and/or underscore characters, and the first character must not be a digit. (T / F)

true

The JVM allocates space for all class variables when the program starts. (T / F)

true

Using Java API methods saves programming time and improves program quality. (T / F)

true

You can use a boolean variable to remember an on/off condition. (T / F)

true

You can use class methods to describe behavior of collections of objects. (T / F)

true

if a memory device loses its data when power is off, we say it is

volatile

In a call to a method in another class, the method name is usually preceded by another word and a dot. What is this other word: a) when the method is a class method? b) when the method is an instance method?

a) When the method is a class method, the preceding word is a class name. b) When the method is an instance method, the preceding word is the name of a calling object (or a more precisely, a reference to that object).

Provide the escape sequences which can be used with a string to accomplish each of the following operations: a) Go to a new line. b) Insert a tab. c) Print a single quote. d) Print a double quote. e) Print a backslash.

a) \n b) \t c) \' d) \" e) \\

Identify any or all of the following which represent good style: a) Include a comment at the end of every line of code. b) Include the author's name in a prolog. c) Save space by putting multiple short statements on the same line. d) Indent subordinate statements. e) Go to a new line for a terminating brace.

b d e

Given: int x = 15; what is the value of x after these two statements execute: x--; x %= 5;

4

Write the output produced by this code fragment: int x = 5; int y = 8; int z; while (y < 20) { z = x + y; x = y; y = z; System.out.println(y); }

13 21

Write the output produced by this algorithm: x ← 2 while x <= 3 { y ← 1 while y <= 3 { print x increment y } newline increment x }

222 333

As a disclaimer i did not put full pseudocodes ad flowcharts here you will need to go to the chapter 1 and chapter 2 tests for the answers for them. i did not put all traces here either.

As a disclaimer i did not put full pseudocodes ad flowcharts here you will need to go to the chapter 1 and chapter 2 tests for the answers for them. i did not put all traces here either.

Assuming stringVal is a String variable that contains a string representation of an int number, and intVal is an int variable, write a Java statement that converts what&#39;s in stringVal to an int and then assigns it to intVal.

Conversion from String to int: intVal = Integer.parseInt(stringVal);

For each of the following declarations, indicate whether it is OK, and if it is not OK, indicate what&#39;s wrong: a) public static final double AVOGADRO_NUMBER; b) public final double MOLECULAR_WEIGHT;

Correctness: a) Not OK. A static constant must be initialized when it is declared. b) OK. (The best practice is to initialize an instance constant in a constructor.)

Select one of the following: a) An OOP object could represent a particular computer. b) An OOP object could represent a particular person. c) An OOP object could represent a colony of ants. d) An OOP object could be the set of immediate threats to a particular chess piece. e) Any of above.

Examples of OOP objects: e) Any of above

Declare and initialize a format specifier string called format, so that it specifies an arbitrary string, a tab, a dollar sign, and a floating point number. The floating point number should include comma separators between every three integer digits and two decimal places to the right of the decimal point. Then, use this specifier in a printf statement to output the string label, "transmission", and the dollar amount, $4,388.69, like this: transmission $4,388.69

Format specification: String format = &quot;%s\t$%,.2f\n&quot;; System.out.printf(format, &quot;transmission&quot;, 4388.69);

As program scope increases, should expand code by increasing the size of existing methods or by adding more methods?

Increase program scope by defining additional methods rather than enlarging existing methods.

The computer program that converts Java bytecode to machine code (or object code) is called the

JVM

Complete the following: a) Local variables (defined in a method) persist for ____________________________. b) Instance variables persist for _________________________________. c) Method parameters persist for _________________________________. d) An index declared in a for loop persists for _____________________________.

Persistence: a) Local variables (defined in a method) persist for as long as the method is executing. b) Instance variables persist for as long as the object exists. c) Method parameters persist for as long as the method is executing. d) An index declared in a for loop persists for as long as the for loop is executing.

Suppose you want to get a Java program's text input from a text file instead of from the keyboard. a) Assuming the input file is called input.txt, provide the appropriate Scanner argument: Scanner fileIn = new Scanner(____________________);

Scanner fileIn = new Scanner(new File("input.txt"));

Select the best answer: a) You can always access a public instance member from a class method. b) You can always access a public class member from an instance method. c) You can never access a public instance member from a class method. d) You can never access a public class member from an instance method.

The best answer: b) You can always access a public class member from an instance method.

Why is the output of a Java compiler more "portable" than the output of a C++ compiler?

The output of a Java compiler is more "portable" than the output of a C++ compiler because Java bytecode is "machine independent." It is able to run on any type of computer

Given the code: double interestRate = 0.05; double balance = 100.00; int interestInDollars = (int) interestRate * balance; System.out.println(interestInDollars); a) Assuming you really do want rounded-down interest in dollars, what&#39;s wrong with the interestInDollars initialization statement?

This code does not compile because the (int) cast operates on only the interestRate variable. Subsequent multiplication by the double variable, balance, promotes the right side to double. And the compiler will not automatically "demote" this double into an int for the assignment.

Each of the following five groups is a set of operators that have the same precedence, but each group has different precedence from the other groups. After each group write a number between 1 and 5 that indicates that group&#39;s relative precedence. Use 1 for the group whose operators have highest precedence (occur first) and 5 for the group whose operators have lowest precedence. To get you started, the first group&#39;s relative precedence is provided. a) addition, subtraction _2_ b) logical "or" ___ c) equality, inequality ___ d) logical "and" ___ e) multiplication, division ___

a) 2 b) 5 c) 3 d) 4 e) 1

Logically, the make and model attributes of each Car object should not change in the life of that object. a) Write Java code that declares constant make and model attributes that cannot be changed after they are initialized by a constructor. Configure your declarations so that get- methods are not needed to read the values of these attributes from outside the class. b) Assuming you are in a separate driver class that has already used a constructor to create and fully initialize an object called car that has constant make and model attributes, write a Java statement that prints these two attributes on one line with one space between them.

a) Declarations: public final String MAKE; public final String MODEL; or: public final String MAKE, MODEL; b) Access: System.out.println(car.MAKE + &quot; &quot; + car.MODEL); or: System.out.printf(&quot;%s %s\n&quot;, car.MAKE, car.MODEL);

Suppose a Car class defines an equals method with this header: public boolean equals(Car car) This equals method returns true if and only if the calling object and the parameter object have the same make and model. Otherwise, it returns false. Now suppose the Car class also defines the following (overloaded) equals method: public boolean equals(Car car, String s) { if (s.equals(&quot;make&quot;)) { return this.make.equals(car.make); } else if (s.equals(&quot;model&quot;)) { return this.model.equals(car.model); } else { return this.equals(car); } } a) In ordinary English, explain what this second equals method does. b) Could the same Car class also define a third equals method with the following heading? public boolean equals(String s, Car car) Explain why or why not.

a) The two-parameter equals method establishes equality on the basis of a specified attribute. If the second parameter is the string "make", the method returns true if and only if the makes are the same, and false otherwise. If the second parameter is the string "model", the method returns true if and only if the models are the same, and false otherwise. If the second parameter is any other string, the method returns true if and only if both makes and models are the same, and false otherwise. b) Yes. The signatures are different because the parameter type sequence changes from (Car, String) to (String, Car). So it&#39;s a different method.

Which (if any) of the following statements is (or are) true: a) In a well-structured program, flow never goes backward. b) Each conditional has exactly two alternative next statements. c) Each conditional always has exactly one previous statement. d) In a well-structured program, it&#39;s OK for flow to go back to a previous non-conditional statement. e) In a well-structured program, it&#39;s OK for flow to go back to a previous conditional. f) In a well-structured program, it&#39;s OK to repeat a particular sequence of operations an arbitrary number of times.

b e f

Using ← for all assignments, write pseudocode for an algorithm that establishes the base and height of a triangle as 8 and 5, respectively. Then it computes the triangle's area. Then it outputs that area.

base ← 8 height ← 5 triangleArea ← base * height / 2 print "area = " triangleArea

A computer program that converts Java source code to Java bytecode is called a

compiler

Write pseudocode to describe an algorithm which computes and prints the sum of the squares of three prompted input values. Use looping with a down-counter that terminates at zero, and use ← for assignments. Use &gt; for the looping condition, and use decrement count for each change in count&#39;s value.

count ← 3 sum ← 0 if count &gt; 0 { print "Enter a value: " input value sum ← sum + value * value decrement count } print sum

Assume the existence of Java code that already includes these two statements: Scanner stdIn = new Scanner(System.in); char entry; Then, implement an input-validation do loop that prompts the user to enter 'y' or 'n' and assigns the entered value to entry. If the entered value is not either 'y' or 'n', the code should repeat the prompt and the input assignment an indefinite number of times until the input is either 'y' or 'n'.

do { System.out.print(&quot;Enter y or n: &quot;); entry = stdIn.nextLine().charAt(0); } while (entry != &#39;y&#39; &amp;&amp; entry != &#39;n&#39;);

Write a statement that declares a variable intended to represent body temperature and initializes it to 37.05.

double bodyTemperature = 37.05;

Assume a Car class includes an equals method, whose heading looks like this: public boolean equals(Car car) a) Write a Java expression that uses this method to compare two Car objects, car1 and car2. b) Assuming the Car class defines just two instance variables, make and model, write Java code that implements this equals method.

equals method use and implementation: a) car2.equals(car1) or: car1.equals(car2) b) public boolean equals(Car car) { return this.make.equals(car.make) &amp;&amp; this.model.equals(car.model); } // end equals

A class is a group of two or more objects. (T / F)

false

All Java API methods are class methods. (T / F).

false

If the name of an argument in a method call is the same as the name of the corresponding parameter in the method&#39;s definition, changing that parameter&#39;s value inside the method also changes the value of the corresponding argument in the calling program. (T / F)

false

If you want the initial value of a particular instance variable to be the default value for that type of variable, you should save space by accepting the default and not performing explicit initialization. (T / F)

false

In addition to comparing numbers, the == operator also compares the contents of strings. (T / F)

false

It's good style to begin all variable names with an upper-case character. (T / F)

false

Java is not sensitive to whether characters are in lower or upper case. (T / F)

false

When input values are arbitrary, you can use sentinel value loop termination to improve input efficiency. (T / F)

false

You can make a variable defined within a method be available outside that method by including the word public in that variable&#39;s declaration. (T / F)

false

You should use static variables to represent properties of individual objects. (T / F)

false

Write a statement that declares a named constant that represents absolute zero and initializes it to -273.15.

final double ABSOLUTE_ZERO = -273.15;

It&#39;s good practice to make constants as local as possible. (T / F)

flase

Write Java code for a method called getWeight. This method should be accessible from outside its class, and it should return the current value of an instance variable called weight, which is declared to be a double.

getWeight method implementation: public double getWeight() { return this.weight; } // end getWeight

what does GHZ stand for

gigahertz

Write the import statement that enables you to use the Scanner class.

import java.util.Scanner;

Suppose you want to get a Java program's text input from a text file instead of from the keyboard. c) Write the two import statement required for this operation.

import java.util.Scanner; import java.io.File;

keyboard (output, input, memory)

input

mouse (output, input, memory)

input

In pseudocode, why is it better to use the word, equals, rather than the familiar equals sign, =, to indicate equality in a condition?

in Java code = means assignment, and using == with strings creates bugs.

Assume that you are looking at a command-prompt window, and the current directory contains an already-compiled version of a Java program called TestProgram. What do you enter after the command prompt to execute that program?

java TestProgram

Write Java source code for a program called Hello, which does nothing more than print the simple output: Hello World For simplicity, do not include a prolog, but otherwise, use good style. For example, use appropriate indentation and include method- and class-termination comments. The program should be able to compile, and the compiled file should be able to run without error.

public class Hello { public static void main(String[] args) { System.out.println("Hello World"); } // end main } // end class Hello

Using good programming style, write the Java source code for a program called DoNothing. Your source code should compile successfully, and the compiled code should execute without error. But this minimal program should not actually do anything at all. That is, it should not contain any executable statements.

public class doNothing { public static void main(String[] args) { } }

Assume that one of the instance variables of an object is a double value called weight. Write Java code for a setWeight method which does no more than assign the value of a double parameter called weight to the corresponding instance variable.

public void setWeight(double weight) { this.weight = weight; }


Ensembles d'études connexes

Ecology Exam 3 Practice Problems

View Set

White Collar Crimes and Political Crimes

View Set