CompSci Midterm

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

List the 6 symbols for the relational operators that can be used to compare primitive data types in Java.

< > <= >= == !=

What is a variable?

A variable is a named memory location whose value can change.

Which of these best describes the relationship between classes and objects? Classes and objects are the same thing. Classes manipulate objects. Objects are used to create classes. Classes are like the a blueprint, they define objects.

Classes are like the a blueprint, they define objects.

Write the algorithm for a program that will assign a BMI status to patients. The doctor will enter a BMI index value and the program will display the BMI status. Use the BMI chart provided. BMI Index Value BMI Status Less than 18.5 Underweight 18.5 to 24.9 Normal weight 25 to 29.9 Overweight 30 or above Obese

Enter BMI_IndexValue IF BMI_IndexValue > 30 Output "Obese" ELSE IF BMI_IndexValue >= 25 Output "Overweight" ELSE IF BMI_IndexValue >= 18.5 Output "Normal weight" ELSE Output "Underweight"

**Given the function definition: DEFINE greet(name, time) greeting = "Good " + time + " " + name IF (name == "Bob") THEN RETURN greeting ENDIF greeting = greeting + "!" PRINTLN greeting RETURN greeting END DEF And the following code statements: banner = "Good morning" greet("Bob", "morning") PRINTLN banner What is the output of this code? Good morning Good morning Bob! Good morning Good morning Bob Good morning Good morning Bob Good morning Bob!

Good morning

Which example below shows polymorphism. Object o = new Object(); Circle c = new Object(); Object o = new Circle(); Circle c = new Circle();

Object o = new Circle();

Create the UML Class Diagram for the following class: Rectangle class two double instance variables: length and width default constructor parameterized constructor passing in length and width accessors and mutators for length and width getArea method that calculates and returns the area getPerimeter method that calculates and returns the perimeter toString method to return a string including the area and perimeter of the rectangle

Rectangle - length: double - width: double + Rectangle() + Rectangle(length: double, width: double) + getLength(): double + setLength(length: double): void + getWidth(): double + setWidth(width: double): void + getArea(): double + getPerimeter(): double + toString(): String

Write a Java statements that declares and instantiates an Array of String objects called olderGen with the following names: "Larry", "Moe", "Curly", and "Disney".

String [] olderGen = {"Larry", "Moe", "Curly", "Disney"};

Which of the following lines of code correctly writes "hello" to the screen? System.out.println(Hello); system.out.println("Hello"); System.out.println("Hello"); System.out.println("Hello")

System.out.println("Hello");

On paper, draw a stack diagram to show the state of memory for all the code at the end of the execution of the performAction method, from another question, before control is passed back to the main method.

***

State the output of the following code sample: int[][] values = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { values[i][j] = (i * j); System.out.print(values[i][j] + " "); } System.out.println(); }

***

charList=['h','a','p','p','y','b','i','r','t','h','d','a','y'] firstWord = [] secondWord = [] flag = false FOR i = 0 TO length(charList) BY 1 DO IF (/* missing 1 */) THEN /* missing 2 */ flag = true ELSE /* missing 3 */ ENDIF Fill in /* missing 1 */, /* missing 2 */, and /* missing 3 */ to complete the algorithm above so that it separates the array of characters into two arrays, firstWord, containing "happy", and secondWord, containing "birthday"

/* missing 1 */ charList[i]=='b' OR flag==true /* missing 2 */ secondWord[i-length(firstWord)] = charList[i] /* missing 3 */ firstWord[i] = charList[i]

State the output of the following code sample: int[][] values = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { values[i][j] = (i + 2j); System.out.print(values[i][j] + " "); } System.out.println(); }

0 2 4 6 1 3 5 7 2 4 6 8 3 5 7 9

Explain the steps that need to happen to take code from it being written to it running and producing output.

1. Code is written in a an IDE or editor. 2. Code is compiled into a class file or byte code 3. The byte code is run by the virtual machine and results are outputted.

Write the pseudocode for a program that will read in a file containing each month name and the amount of rainfall for that month for that year in inches. The program will output the month with the lowest amount of rainfall and the amount of rainfall for that month. Here is a sample of the file's data: January 3.48 February 2.04

1. Enter a filename 2. Open the file 3. Set lowMonth to the first month read from the file 4. Set lowRain to the first rainfall read from the file 5. WHILE (there are more lines of data) a. Read in a month and rainfall b. IF(lowRain > rainfall) - lowRain = rainfall - lowMonth = month c. END IF 6. END WHILE 7. Output lowMonth and lowRain

Write an algorithm for a program that will ask the user for the number of participants they have. The program will then ask for each participant's name and golf score, and, at the end of the input, will display the participant's name with the lowest score. You do not need to worry about tie scores.

1. Enter numParticipants 2. Set count to 1 3. Enter name 4. Set lowName to name 5. Enter score 6. Set lowScore to score 7. WHILE (count < numParticipants) Enter name and score IF score < lowScore Set lowScore = score Set lowName = name END IF Set count = count + 1 Display lowName

List the three steps that are included in every properly implemented loop structure.

1. Initialize loop control variable 2. Test loop control variable 3. Update loop control variabl

Place the visibility modifiers in order from most restricted to least restricted. none, public, protected , private

1. private 2. none 3. protected 4. public

What is written to the output file from the following code if the input file contains the values: 2.0 10.0? import java.io.File;import java.io.FileNotFoundException;import java.io.PrintWriter;import java.util.Scanner;public class Items{public static void main(String[] args) throws FileNotFoundException{Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); double total = 0; while (in.hasNext()) { double price = in.nextDouble(); price *= 2.2; out.printf("The increase is: %10.2f%n", price); total += price; } out.printf("The total increase is: %10.2f%n", total); in.close(); out.close();}} The increase is: 4.4 The total increase is: 4.4 The increase is: 22.0 T

The increase is: 4.40 The increase is: 22.00 The total increase is: 26.40

What is stored in the memory location of the variable below? String s = "Welcome";

The reference to the memory location that contains the String, "Welcome".

word = ['Y', 'P', 'P', 'A', 'H'] FOR i = 0 TO length(word) BY 1 DO FOR J = 0 TO (i) BY 1 DO PRINT word[i - j] ENDFOR PRINTLN "!" ENDFOR What is the output of executing this code segment? H A P P Y! Y! YP! YPP! YPPA! YPPAH! Y PY PPY APPY HAPPY! HAPPY! Y! PY! PPY! APPY! HAPPY!

Y! PY! PPY! APPY! HAPPY!

What values are outputted in the output statement in the main method? import java.util.*;public class Test {public static void main(String[] args) { int[] nums = {1, 2, 3, 4}; performAction(nums); System.out.println(Arrays.toString(nums));}public static void performAction(int [] data) { for (int i =0; i < data.length; i++) { data[i] = data[i] * 5; }}}

[ 5, 10, 15, 20]

What values are outputted in the output statement in the main method? import java.util.*;public class Test {public static void main(String[] args) { int[] nums = {5, 10, 15, 20}; performAction(nums); System.out.println(Arrays.toString(nums));}public static void performAction(int [] data) { for (int i =0; i < data.length; i++) { data[i] = i * 2; }}} On paper, draw a stack diagram to show the state of memory for all the code at the end of the execution of the performAction method before control is passed back to the main method.

[0, 2, 4, 6 ]

What is the output of the following two code segments? [a] System.out.println(6 + 7 > 0 && 6 / 0 < 7); [b] System.out.println(24 / 8 < 15 || 2 / 0 > 9);

[a] error [b] true

Answer the questions about the following code segment. int num = 486; while (num > 300){ num = num % 2; } [a] How many times does this loop execute? [b] What is the value of num when the loop ends?

a) 1 b) 0

What is displayed in the following code segment? int numerator = 22; int denominator = 4; System.out.println(numerator / denominator); [a] System.out.println(numerator % denominator); [b]

a) 5 b) 2

Answer the questions about this code segment. int count = 0; int total = 0; while (count <= 5) { total = total + 4; count++; } [a] How many times does this loop execute? [b] What is the value of count when the loop ends? [c] What is the value of total when the loop ends?

a) 6 b) 6 c) 24

Fill in the blanks in the main method code below: [a] [b] [c] main ([d] args) { }

a) Public b) static c) void d) String

For each error shown below state if it is a compile-time error, run-time error, or no error. a) system.out.println("Greetings, Planet Earth!") ; b) System.out.println("Hello World!") c) long distance = 785456784456; d) System.out.println(50 / 0); e) Int x = 43; f) System.out.print(23 % 144);

a) compile-time error b) compile-time error c) compile-time error d) run-time error e) compile-time error f) no error

**Which answer best explains how this code snippet would or would not work? int k; for(int i = 0; i < 5; i++) k = i * 2; System.out.println(i); a) it wouldn't work because scope is violated b) it would work and would print 5 c) it wouldn't work because there are no brackets D) it would work and would print out every value of i

a) it wouldn't work because scope is violated

What is the output of the following lines of code: [a]System.out.println("sum is " + 10 + 20); [b] System.out.println("sum is + 10 + 20");

a) sum is 1020 b) sum is + 10 + 20

Given the function definition for computing the displacement of an object: DEFINE calculate (a, b, c) solution = a * c + 0.5 * b * c * c RETURN solution ENDDEF x = 3 y = 12 z = 9 solution = calculate(x, y, z) Which of the following statements is true after the call to calculate(x, y, z) has completed execution? a) The order of inputs to the function call is unimportant; the function definition declares how the inputs are used. e.g., calculate(x, y, z) == calculate(y, x, z) b) a, b, and c are undefined c) a = 3, b = 12, and c = 9 d) calculate is called with up to 3 variables e) If the value of a changes inside the calculate function, the value of x will also be changed.

a, b, and c are undefined

Fill in the blanks with the appropriate code: public class Demo{ public static void main(String[] args) throws FileNotFoundException{ // check and read command line argument for file name String inputFileName; if (args.length > 0) { _______[a]____________; } else { Scanner input = ______[b]_____________; System.out.print("Enter an input file"); inputFileName = _______[c]________; } ______[d]_____ inputFile = new File(inputFileName); Scanner in = ______[e]___________; }

a. inputFileName = args[0] b. new Scanner(System.in) c. input.next() d. File e. new Scanner(inputFile)

Write the code to declare and initialize a variable called middle that is set to the character A.

char middle = 'A';

A part of a program that contains information about the program but has no effect when the program runs is called a [a].

comment

Given the following declaration statement, write a statement that increments the value in the variable count. int count = 0;

count++; , count = count + 1; count += 1;

Write a single Java statement to store the number of elements of a double array called values into the int variable called countValues. You may assume that all variables have been declared and the array has been initialized.

countValues = values.length;

How would you print out the value below rounded to two decimal places: double num = 345.7485; a) System.out.printf(%.2f + num); b) System.out.printf(%.2f, num); c) System.out.printf("%.2f" + num); d) System.out.printf("%.2f", num);

d) System.out.printf("%.2f", num);

What does the virtual machine do? a) runs byte code b) runs the class file c) generates source code d) both a and b.

d) both a and b.

the process of finding and removing errors in called:

debugging

What code will return the string, Lovegood, from the string: String s = "Luna Lovegood" a) s.substring(5) b) s.substring(6) c) s.substring(5, s.length()) d) s.substring(6, s.length()) e) both a and c f) both b and d

e) both a and c

What keyword is used to indicate that a class is a sub-class of another class. interface extends super this

extends

(true/false) A sub-class can access the private data in it's parent or super class directly.

false

Compile errors are the hardest errors to find.

false

Write a constant statement to hold the value of the sales tax in Virginia, which is 4.3%.

final double SALES_TAX = 0.043;

Name two primitive Java data types that represent floating-point numbers.

float and double

Write the code to declare and initialize a float variable called rate with the rate of 7.5%.

float rate = 0.075f;

Write an enhanced for loop, or foreach loop, that will output the values of the array below: int [] nums = {4, 5, 6, 7, 8};

for(int e: nums) { System.out.println(e); }

Write a conditional statement that stores true in a boolean variable, small, if the int variable height is less than the int variable miniscule. Otherwise, store false in the boolean variable, small. You may assume that all variables have been declared and initialized.

if (height < miniscule) { small = true; } else { small = false; }

Write the if statement that returns true if the int value of x is not in the range between 0 and 9, inclusively. x has been initialized.

if (x < 0 || x > 9)

Name four primitive Java data types that represent whole numbers.

int, long, byte, short

The command to compile a Java program is:

javac

Which of the following answers best describes how space in memory is allocated in the code below? Pillow myPillow = new Pillow(); Bed myBed; myPillow variable references a Pillow object and myBed variable does not reference a Bed object space has not been allocated for a Pillow object and space has been allocated for a Bed object both have space allocated for the objects neither have space allocated for the objects

myPillow variable references a Pillow object and myBed variable does not reference a Bed object

Write the class and parameterized constructor to build a sub-class from the class Vehicle below called Car. The Car class contains a String attribute for engineType. The Car class parameterized constructor will accept the numWheels and engineType. public class Vehicle { private int numWheels; public Vehicle() { this.numWheels = 4; } public Vehicle(int numWheels) { this.numWheels = numWheels; } }

public class Car extends Vehicle { String engineType = "motorized"; public Car(int numWheels, String engineType){ super(numWheels); this.engineType = engineType; } }

Write a method that will return the result of an Integer number, which is passed in, raised to the third power. Here are method calls and the expected output: cube(2) returns→ 8 cube(-1) returns→ -1 cube(3) returns→ 27

public static int cube(int num) { return num * num * num; }

Write a method that is passed a positive integer value, num. The method will output the total of the numbers 1 + 2 + 3 + ... + num. Here is a sample method call and the expected output: findTotal(5) prints→ 15 (note 15 = 1 + 2 + 3 + 4 + 5)

public static void findTotal(int num) { int total = 0; for (int i = 1; i <= num; i++) { total += i; } System.out.println(total);

What is an example of a method that is overridden from the following method in the Circle class: public void setRadius(double radius) public void setRadius(int radius) public double setRadius(double newRadius) public void setRadius(double Radius) public double getRadius()

public void setRadius(double Radius)

What is an example of a method that is overloaded from the following method in the Circle class: public void setRadius(double radius) public void setRadius(int radius) public void setRadius(double newRadius) public void setRadius(double Radius) public double getRadius()

public void setRadius(int radius)

While running a program, it unexpectedly stops. What type of error is that? runtime or compilation

runtime

Write the code that will determine if the two strings, s1 and s2 are equal.

s1.equals(s2)

(true/false) Inheritance uses an "is a" relationship as a relationship between the subclass and the super class.

true

The class name must be the same as the filename in a Java program. (T/f)

true

What are the two values that a boolean variable can have? [a] [b]

true and false

What should the values of x and y be in order to fill all the elements of the following array with values of -1? int[] myArray = new int[10]; int i; int x; int y; for (i = x; i < y; i++){ myArray[i] = -1; }

x = 0, y = the length of myArray

x = 3 y = 9 z = 5 IF y % x == 0 THEN IF y >= z THEN x = x * x ELSE z = z * z ENDIF ELSE IF z >= x THEN IF y >= z THEN y = y * y ENDIF ELSE z = z * z ENDIF ENDIF IF y % x == 0 THEN x = x + 3 ELSE y = y * 2 ENDIF PRINTLN "x = ", x PRINTLN "y = ", y PRINTLN "z = ", z What is printed as a result of this code segment?

x = 12 y = 9 z = 5

Consider the following code segment. r = 5 h = 9 Please select the most correct code fragment that will result in calculating the surface area of a cylinder, given the equation: Surface Area = 2pi*r^2 + 2pi*r*h x = 2 * 3.14 * r y = x * r z = h * x surfaceArea = z + x x = 2 * 3.14 * r y = x * r z = h * x surfaceArea = y + z x = 2 * 3.14 * r * r y = h * x surfaceArea = y + x x = 2 y = x * 3.14 * r * r z = x * 3.14 * h surfaceArea = y + z x = r y = 6.28 * x z = 6.28 * x * h surfaceArea = y + z

x = 2 * 3.14 * r y = x * r z = h * x surfaceArea = y + z

Create and fill the array that would be stored after the following code executes: int[] list = {-3, 5, 7, -2, 4, 6, -1}; for (int i = 1; i < list.length; i++) { list[i] = list[i] - (list[i] / list[i-1]); } Please make your answer easy to read. Your answer should look like this: {ans, ans,...} or something similar.

{-3, 6, 6, -2, 6, 5, -1}

Create and fill the array with the values that would be stored after the code below executes: int[] data = new int [8]; data[6] = 2; data[0] = -6; data[3] = 9; int x = data[6]; data[x] = 33; data[1] = data[2] + data[3] + data[5]; Please make your answer easy to read. Your answer should look like this: {ans, ans,...} or something similar.

{-6, 42, 33, 9, 0, 0, 2, 0}

Create and fill the array that would be stored after the following code executes: int[] list = {6, 9, -4, 5, 10, -8, 44}; for (int i = 0; i < list.length; i++) { list[i] = list[i] - (list[i] / list[0]); } Please make your answer easy to read. Your answer should look like this: {ans, ans,...} or something similar.

{5, 8, -4, 4, 8, -7, 36}

Answer the question about the following code segment. int i = 4; do { System.out.print(i + "%"); i--; } while (i > 5); What is the output of the loop?

4%

Consider the following code segment. p = 1 s = 3 e = 5 e = s s = p * e p = e e = s p = s + e e = p / s s = p After the above code is executed, what is the value of s?

6

What is the value of m after this operation? int b = 5; int m = 20; m -= 6 + 2 * 3 + ++b - 8 / 2;

6

Class Car has three String fields: make, model, and color. It has two constructors. The default constructor sets the fields to the string, ("None Given"). The overloaded constructor has three String parameters and initializes make, model, and color with these values. Fill in the blanks in this partial implementation of the Car class. You may assume that there are assessor methods following the standard naming convention for each of the three instance variables even though only the getter and setter for make is shown here. public class Car { ______[a]_________ String make, model, color; public Car(){ make = __________[b]____________________; model = __________[c]____________________; color = ___________[d]___________________; } public Car(String make, String model, String color){ ______[e]_________= make; ______[f]_________= model; ______[g]_________= color; } // getters and setters for model and color are not shown,

a. private b. "None Given" c. "None Given" d. "None Given" e. this.make f. this.model g. this.color h. return make i. null j. this.make = make k. String l. result m. return result

What code will return the string, Luna, from the string: String s = "Luna Lovegood" a) s.substring(1, 4) b) s.substring(0, 4) c) s.substring(0, 3) d) s.substring(1, 5)

b) s.substring(0, 4)

Given the function definition: DEFINE add(a, b, c) max = 0 IF ((a < b) AND (a < c)) THEN max = b + c RETURN max ELSE IF ((b < a) AND (b < c)) THEN max = a + c RETURN max ELSE max = a + b RETURN max ENDIF PRINTLN max ENDDEF Which of the following statements best describes the execution of the function call: add(7, 4, 13) a) Value of max = 11 b) Nothing will ever be returned from this function c) Nothing will ever be printed from this function d) After printing the max product, add will return the max

c) Nothing will ever be printed from this function


संबंधित स्टडी सेट्स

Ch. 10 - Writing Correct and Effective Sentences

View Set

AP Language and Composition: Chapter 8 Vocab

View Set

Plant Responses to Environment Launchpad

View Set

unit 5.1, 5.2, 5.3, 5.4, 5.8, 5.9 assesment

View Set

A+ 220-802 - Domain 3 - Mobile Devices - 9%

View Set

Chapter 6: Behaviorism & Learning Theory

View Set

Managerial Accounting - Chapter 3

View Set

Statistical Process Control (SPC)

View Set