Barrons Test: Quiz Questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Which of the following will evaluate to true only if boolean expressions A, B, and C are all false?

!( A || B || C)

Suppose that strA = "TOMATO", strB = "tomato", and strC = "tom". Given that "A" come before "a" in dictionary order, which is true?

!(strA. equals(str.B)) && strC.compareTo(strB) < 0

This question refers to the following declaration. String line = "some more silly stuff on strings!"; //the words are separated by a single space What string will str refer o after execution of the following? int x = line.indexOf("m"); String str = line.substirng(10. 15) + line.substirng(25, 25 + x);

"sillyst"

Supposed that addition and subtraction had higher precedence than multiplication and division. Then the expression 2 + 3 * 12/ 7 - 4 + 8 would evaluate to which of the following?

5

What output will be produced by this program? public class Mystery { public static void strangeMethod(int x, int y) { x += y; y *= x; System.out.pritnln(x + " " + y); } public static void main(String[ ] args) { int a = 6, b = 3; strangeMethod(a, b); System.out.pritnln(a + " " + b); } }

9 27 6 3

The following fragment intends that a user will enter a list of positive integers at the keyboard and terminate the list with a sentinel. int value = 0; final int SENTINEL = -999; while (value ! = SENTINEL) { //code to process value . . . value = . . . ; //read user input } The fragment is not correct. Which is a true statement?

The code will always process a value that is not on the list

Consider teh following code segment, applied to list, an ArrayList of Integer values. int len = list.sex(); for (int i = 0; i < len; i++) { list.add(i + 1, new Integer(i)); Object x = list.set(i, new Integer(i + 2)); It list is initially 6 1 8 what will it be following execution of the code segment?

2 3 4 2 1 8

Consider this program: public class CountStuff { public static void doSomething() { int count = 0; . . . //code to do something - no screen output produced count++ } public static void main(String[] args) { int count = 0; System.out.pritnln("How many iterations?"); int n = . . . ; //read user input for (int i =1; i <= n; i++) { doSomething(); System.out.pritnln(count); } } } If the input value for n is 3, what screen output will this program subsequently produce?

0 0 0 0

Consider the following method that will alter the matrix mat.. . . Suppose mat is originally 1 4 9 0 2 7 8 6 5 1 4 3 After the method call matStuff(mat, 2) matrix mat will be

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

Consider a class that has this private instance variable private int [] [] mat; If a 3 * 4 matrix mat is 1 3 5 7 2 4 6 8 3 5 7 9 then later (1) will change mat to

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

What value is stored in result if int result = 13 - 3 * 6 / 4 % 3;

12

Which of the following correctly initializes an array arr to contain four elements each with value 0? I: int[] arr = {0, 0, 0, 0}; II: int [] arr = new int[4]; III: int [] arr = new int[4]; for (int i = 0; i M arr.length; i++) arr[i] = 0;

I, II , and III

Which statement about the Name class is false?

Since the Name class has a compareTo method, it must provide an implementation for an equals method.

What output will be produced by the following? System.out.print("\\* This is not\n a comment *\\");

\* This is not a comment*\

A program is to simulate plant life under harsh condition.s In the program, plants die randomly according to some probability. Here is part of a Plant class defined in the program: public class Plant { /**Probability that plant dies is a real number between 0 and 1. */ private double probDeath; public Plant (double plantProbDeath, <other parameters>) { probDeath = plantProbDeath; < initialization of other isntance cariables> } /** Plant lives or dies. */ public void liveOrDie() { /* statement to generate random umber*/ if(/* test to determine if plant dies */ ) <code to implement plant's death> else <code to make plant continue living.> } //Other variables and methods are not shown. } Which of the following are correct replacements for (1) /*statement to generate random number*/ and (2) /* test to determine if plant dies */?

(1) double x = Math.dranodm(); (2) x < probDeath

What will be output from the following code segment, assuming it is in the same class as the doSomething method? int[] arr = {1, 2, 3, 4]} doSomething(arr); System.out.print(arr[1] + " "); System.out.print(arr[3]); . . . . . public void doSomething(int[] list) { int[] b = list; for (int i = 0; i < b.length; i++) b[i] = i; }

1 3

What will the output be for the following poorly formatted program segment, if the input value for num is 22? int num = call to a method that reads an inteer; if (num > 0) if (num % 5 ==0) System.out.println(num); else System.out.println(num + " is negative");

22 is negative

Which statement about parameters is false?

Two overloaded methods in the same class must have parameters with different names

Consider this code segment int x = 10, y = 0; while (x > 5) { y = 3; while (y < x) { y *= 2; if ( y % x == 1) { y += x; } } x -= 3; } Systen.out.pritnln(x + " " + y); What will be output after execution of this code segment?

4 12

public class Temperature { private String scale //valid values are "F" or "C" private double degrees; /** constructor with specified degrees and scale */ public Temperature( double tempDegrees, String tempScale) { /*implementation not shown */ } /**Mutator. Converts this Temperature to degrees Fahrenheit. * Returns this temperature in degrees Fahrenheit. * Precondition: Temperature is a valid temperature * in degrees Celsius. */ public Temperature toFahrenheit() { /* implementation not shown */} /**Mutator. Converts this Temperature to degrees Celsius. *D Returns this temperature in degrees Celsius. * Precondition: Temperature is a valid temperature * in degrees Fahrenheit. */ public Temperature toCelsius() { /* implementation not shown */} /** Mutator * Returns this temperature raised by amt degrees. */ public Temperature lower (double amt) { /*implementation not shown */} /** Returns true if tempDegrees is a valid temperature * in the given temperature scale, false otherwise. */ public static boolean is ValidTemp(double tempDegrees, String tempDegrees, String tempScale) { /* implementation not shown */} //Other methods are not shown } A client method contains the code segment: Temperature t1 = new Temperature(40, "C"); Temperature t2 = t1; Temperature t3 = t2.lower(20); Temperature t4 = t1.toFahrenheit(); Which statement is true following execution of this segment?

t1, t2, t3, and t4 all represent the identical temperature, in degrees Fahrenheit

Which of the following correctly replaces /*more code*/ in the Transaction constructor to initialize the tickList array?

tickList[i] = new Ticket(theRow, theSeat, thePrice);

The following program segment is intended to find the index of the first negative integer in arr[0] . . . arr[N-1], where arr is an array of N integers int i = 0; while (arr[i] >= 0} { i++; } location = i; This segment will work as intended

whenever arr contains at least one negative integer.

Refer to the following code segment. You may assume that array arr1 contains elemtns arr1[0], arr1[1] . . . , arr1[N-1], where N = arr1.length int count = 0; g for (int i = 0; i < N; i++) if (arr[i] != 0) { arr1[count] = arr1[i]; count++; } int[] arr2 = new int[count]; for (int i = 0l i < count; i__) arr2[i] = arr[i]; If array arr1 initially contains the elemtns 0, 6, 0, 4, 0, 0, 2 in this order, what will arr2 contain after execution of the code segment?

6, 4, 2

public class Tester { public void somemethod(int a, int b) { int temp = a; a = b; b = temp; } } public class TesterMain { public static void main (String[] args) { int x = 6, y= 8; Tester tester = new Tester(); tester.someMethod(x,y)'; } } Just before the end of execution of this program, what are the values of x, y, and temp, respectively?

6, 8, ?, where ? means undefined

/** Returns true if the 4-digit integer n is valid, * false otherwise */ boolean checkNumber(int n) { int d1, d2, d3, checkDigit, nRemaining, rem; //strip off digits checkDigit = n % 10; nRemaining = n / 10; d3 = nRemaining % 10; nRemaining /= 10; d2 = nRemaining % 10; nRemaining /= 10; d1 = nRemamining % 10; //check validity rem = (d1 + d2 + d3) % 7; return rem == checkDigit; } A program invokes method checkNumber with the statment boolean valid = checkNumber(num); Which of the following values of num will result in valid having a value of true?

6144

Consider the following code segment: int [] [] mat = {{1, 3, 5}, {2, 4, 6} {0, 7 , 8} {9, 10, 11} for (int col = 0; col < mat[0].length; col++) for(int row = mat.length -1; row > col; row--) System.out.println(mat[row][col])' When this code is executed, which will be the fifth element printed?

7

Consider the following code fragment Object intObj = new Integer(9); System.out.pritnln(intObj); You may assume that the Integer class has a toSTring method. What will the output as a result of running the fragment?

9

What output will be produced by this code segment? (Ignore spacing) for (int i = 5; i >= 1; i--) { for (int j = i; j >= 1; j--) System.out.print(2 * j -1); System.out.pritnln(); }

9 7 5 3 1 7 5 3 1 5 3 1 3 1 1

The question refers to the following class. public class IntObject { private int num; public IntObject() //default constructor { num = 0; } public IntObject(int n) //constructor {num = n;} public void increment() //increment by 1 {num++;} } Just before exiting this program, what are the object values of x, y , and a, respectively?

9, 9, 9

Refer to the following code segment. You may assume the arr is an array of int values. int sum = arr[0], i = 0; while (i < arr.length) { i++; such += arr[i]; } Which of the following will be the result of executing the segment?

A run-time error will occur

Consider writing a program that produces statistics for longs lists of numerical data. Which of the following is the best reason to implement each list with an array of int (or double), rather than an ArrayList of Integer(or Double) objects?

An array of primitive number types is more efficient to manipulate than an ArrayList of wrapper objects that contain numbers.

which of the following is a correct replacement for /* declare array of BingoCard */

BingoCard[] playters = new BingCard[NUMPLAYERS];

In the folloiwing code segment, you may assume that a, b , and n are all type int. if (a != b && n/ (a-b) > 90) { /*statement1*/ } else { /*statement2*/ } /*statement3*/ What will happen is a == b is false?

Either /*statment1*/ or /*statement2*/ will be executed

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } Which of the following correctly constructs a date object in a client class?

Date d= new Date (2, 14, 1947);

public class Book { private String title; private String author; private boolean checkoutsStatus; A client program has this declaration Book[] bookList = new Book[SOME-NUMBER]; Suppose book List is initializes so that each Book in the list has a title, author, and checkout status. The following piece of code is written , whose intent is to change the checkout status of each book in bookList. for (Book b : bookList) b. changeStatus(); Which is true about this code?

Each book in the bookList array will have is checkout status changes, as intended

Given that n and count are both of type int, which statement is true about the following code segments? I for (count = 1; count <= n; count ++) System.out.println(count); II count = 1; while (count <= n){ System.out.println(count); count++ }

I and II are exactly equivalent for all input values n

Consider a class MatrixStuff that has a private instance variable: private int [] [] mat; the method does not work as intended. Which of the following changes will correct the problem? I Change line 10 to and make no other changes II Change lines 10 and 11 to and make no other changes III: Change lines 10 and 11 to and make no other changes

I and II only

Consider the squareRoot method defined below. /** Returns a Double whose value is the square root * of the value represented by d. */ public Double squareRoot(Dobule d) { /*implementation code */ } Which /*implementation code */ satisfies the postcondition? I: double x= d; x = Math.sqrt(x); return x; II: return new Double(Math.sqrt(d.doubleValue())); III: return Double(Math.sqrt(d.doubleValue()));

I and II only

The method changeNegs below should replace every occurrence of a negative integer in its matrix parameter with 0. Which is a correct replacement for /* code*/? I for (int r =0; r <mat.length; r++) for (int c = 0; c < mat[r].length; c++) if (mat[r][c] < 0) mat[r][c] = 0; II . . . .

I and II only

Two coins are said to match each other if they have the same name or the same value. You may assume that coins with the same name have the same value and coins with the same value have the same name. A boolean method find is added to the Purse class Which is a correct replacement for /*code to find match */?

I and II only

Which of the following initializes an 8 X 10 matrix with integer values that are perfect squares?

I and II only

public class Temperature { private String scale //valid values are "F" or "C" private double degrees; /** constructor with specified degrees and scale */ public Temperature( double tempDegrees, String tempScale) { /*implementation not shown */ } /**Mutator. Converts this Temperature to degrees Fahrenheit. * Returns this temperature in degrees Fahrenheit. * Precondition: Temperature is a valid temperature * in degrees Celsius. */ public Temperature toFahrenheit() { /* implementation not shown */} /**Mutator. Converts this Temperature to degrees Celsius. *D Returns this temperature in degrees Celsius. * Precondition: Temperature is a valid temperature * in degrees Fahrenheit. */ public Temperature toCelsius() { /* implementation not shown */} /** Mutator * Returns this temperature raised by amt degrees. */ public Temperature lower (double amt) { /*implementation not shown */} /** Returns true if tempDegrees is a valid temperature * in the given temperature scale, false otherwise. */ public static boolean is ValidTemp(double tempDegrees, String tempDegrees, String tempScale) { /* implementation not shown */} //Other methods are not shown } The formula to convert degrees Celsius C to Fahrenheit F is F = 1.8 C + 32 For example, 30 degrees C is equivalent to 86 degrees F An inFahrenehit() accessor method is added to the Temperature class. Here is its implementation: /** Returns an equivalent temperature in degrees Fahrenheit. * Precondition: The temperature is a valid temperature * in degrees Celsius. * Postcondition: * - An equivalent temperature in degrees Fahrenheit has been returned * - Original temperature remains unchanged. */ public Temperature inFahrenheit() { Temperature result; /* more code */ return result; } Which of the following correctly replaces /* more code so that the postcondition is acheived? I: result = new Temperature (degrees * 1.8 + 32, "F"); II: result = new Temperature (degrees * 1.8, "F"); result = result.raise(32); III: degrees *= 1.8; this = this.raise(32); result = new Temperature (Degrees, "F");

I and II only

Consider the following code segment. Inter i = new Integers(20); /* more code*/ Which of the following replacements for /*ore code */ correctly set i to have an Integers value of 25? I: i = new Integer(25); II: i.intValue() = 25; III: Integer j = new Integer (25); i = j

I and III only

This question refers to the getString method shown below. public static String getString (STring s1, String s2) { int index = s1.inexOf(s2); return s1.substring(index, index + s2.length()); } Which is true about getString? It may return a string that I: Is equal to s2 II: Has no characters in common with s2 III: Is equal to s1

I and III only

Which of the following pairs of declarations will cause an error message? I double x = 14.7; int y = x; II double x = 14.7; int y = (int) x; III int x = 14; double y = x;

I only

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } A method in a client program for the Date class has the following declaration. Date d1 = new Date(mo, da, yr); Here, mo, da, and yr are previously defined integer variables. The same method now creates a second Date object d2 that is an exact copy of the object d1 refers to. Which of the following code segment will not do this correctly? I: Date d2 = d1; II: Date d2 - new Date(mo, da, yr); III: Date d2 = new Date(d1.month(), d1.day(), d1.year());

I only

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } here is a client program that uses Date objects: public class BirthdayStuff { public static Date findBirthday() { /* code to get birthDate */ return birthDate; } public static void main(String[] args) { Date d= findBirthday(); . . . } } Which for the following is a correct replacement for /* code to get birthDate */? I: System.out.pritnln("Enter birthdya: mo, day, yr: "); int m = . . . ; //read user input int d = . . . ; //read user input int y = . . . ; //read user input Date birthDate = new Date(m, d, y); II: System.out.println("Enter birthdate: mo, day, yr: "; int birthDate.montg() = . . . ; //reda user input int birthDate.day() = . . . ; int birthDate.year() = . . . ; Date birthDate = new Date (birthDate.month(), birthDate.day(), birthDate.year()); III: System.out.pritnln("Enter birthdate: mo, day, yr: "); int birthDate.month = . . . ; //read user input int birthDate.day = . . . ; //read user input int birthDate.year = . . . ; //read user input Date birthDate = new Date (birthDate.month, birthDate. day, birthDate.year);

I only

public class Name { private String firstName; private String lastName; public Name(String first, String last) //constructor { firstName = first; lastName = last; } public String toString() { return firstName + " " + lastName;} public boolean equals(Object obj) { Name n = (Name) obj; return n.firstName.equals (firstName) && n.lastName.equals(lastName); } public itn compareTo(Name n) { /* more code */ } } The compareTo method implements the standard name-ordering algorithm where last names take precedence over first names. Lexicographic or dictionary ordering of Strings is used. For example, the name Scott Dentes come before Nick Else, and Adam Cooper comes before Sara Cooper Which of the following is a correct replacement for /*more code*/? I: int lastComp = lastName.compareTo(n.lastName); if (lastComp != 0) return lastComp; else return firstName.compareTo(n.firstName); II: if (lastName,equals(n.lastName)) return firstName.compareTo(n.firstName); else return 0; III: if (!(lastName.equals(n.lastName))) return firstName.compareTo(n.firstName); else return lastName.compareTo(n.lastName);

I only

This question is based on the Point class below. The method changeNegs below takea a matrix of Point objects as parameter and replaces every Point Which is a correct replacement for /*code*/?

I, II, and III

Which of the following program fragments will produce this output? (Ignore spacing) 2 - - - - - - 4 - - - - - - 6 - - - - - - 8 - - - - - - 10 - - - - - - 12 I: for (int i = 1; i<= 6; i++) { for (int k= 1; k <= 6; k++) if (k == i) System.out.pritnln(2 * k); else System.out.print("-"); System.out.println(); } II: for (int i = 1; i <= 6; i++) { for(int i = 1; i <= 6; i++) System.out.print("-"); System.out.print(2 * i); for (int k = 1; k <= 6 - i; k++) System.out.println("-"); System.out.pritnln(); } III: for (int i = 1; i <= 6; i++) { for (int k = 1; k < = i -1; k++) System.out.print("-"); System.out.print(2 * i ); for (in k = i +1; k <= 6; k++) System.out.print("-"); System.out.println(); }

I, II, and III

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } Consider the implementation of a write() method that is added to the Date class. /** Write the date in the form m/d/y, for example 2/17/1948. */ public void write() { /*implementation code*/ } Which of the following could be used as /* implemetnation code*/? I: System.out.pritnln(month + "/" + day + "/" + year); II: System.out.pritnln(mounth() + "/" + day() + "/" + year()); III: System.out.pritnln(this);

I, II, and III

A program has a String variable fullName that sores a first name, followed by a space, followed by a list name. There are no spaces in either the first or last name. Here are some examples of full are some examples of fullName values: "Anthony Coppola", "Jimmy Carroll", and "Tom DeWire". Consider this code segment that extracts the last name from a fullName variable, and stores it in lastName with no surrounding blanks: int k = fulName.indexOf(" "); //find index of blank String lastName = /* expression */ Which is a correct replacement for *expression*/? I: full Name.substring(l); II: fullName.substirng(k + 1); III: fullName.substring(k + 1, fullName.length());

II and III only

A two-dimensional array rainfall that contains double values will be used to represent the daily rainfall for a given year. In this scheme, rainfall[month][day] represent the amount of rain on the given day and month. For example, . . . . Which of the following is a correct replacement for /*more code*/ so that the postconidtion for the method is satisfied?

II and III only

Consider the method reverse. /** Returns n with its digits reversed. * -Example: If n = 234, method reverse returns 432. * Precondition: n > 0. */ int reverse (int n) { int rem, revNum = 0; /* code segment */ return revNum; } Which of the following replacements for /*code segment */ would cause the method to work as intended? I: for (int i = 0; i <= n; i++) { rem = n % 10; revNum = revNum * 10 + rem; n /= 10; } II: while (n != 0) { rem = n % 10; revNum = revNum * 10 + rem; n /= 10; } III: for (int i = n; i != 0; i /= 10) { rem = i % 10; revNum = revNum * 10 + rem; }

II and III only

Consider these declarations String s1 = "crab"; String s2 = new String("Crab"); String s3 = s1; Which expression involving these strings evaluates to true? I: s1 = s2 II: s1.equals(s2) III: s3.equals(s2)

II and III only

Consider this program segment. int newNum = 0, temp; int num = k; //k is some predefined integer value >= 0 while (num > 10) { temp = num % 10; num /= 10; newNum = newNum * 10 + temp; } System.out.print(newNum); Which is true statement about the segment? I If 100 <= num <= 1000 initially, the final value of newNum must be in the range 10 <= newNum <= 100. II There is no initial value of num that will cause an infinite while loop. III If num <= 10 initially, newNum will have a final value of 0.

II and III only

This question refers to the following method Now consider this code segment. public final int SIZE = 8; String [] [] mat = new String [SIZE][SIZE]; Which of the following conditions on a matrix mat of the type declared in the code segment will by itself guarantee that isThere(mat, 2, 2, "$") will have the value true when evaluated? I: The elements in row 2 and column 2 is "$" II: All elements in both diagonals are "$" III: All elements in column 2 and "$"

III only

public class Address { private String name; private String street; private String city; private String state; private String zip; //constructors . . . . //accessors public String getName() { return name; } public String getStreet() {return street;} public String getCity() {return city;} public String getState() {return state;} public String getZip() {return zip;} } public class Student { private int idNum; private double gpa; private Address address; //constructors . . . //accessors public aDdress get Address() {return address; } public int getIdNum() {return idNum;} public double getGpa {return gpa} } Here is a method that locates the Student with the highest idNum. /** Returns Student with highest idNum * Precondiiton: Array stuArr of Student is initialized */ public static Studetn locate (Student[] stuArr) { /* method boyd */ } Which of the following could replace /* method body */ so that the method works as intended? I: int max = stuArr[0].getIdNum(); for(Student student : stuArr) if (stduent.getIdNum() > max) { max = studen.getIdNum(); return student; } return stuArr[0]; II: Student highestSoFar = stuArr[0]; int max = stuArr[0].getIdNum(); for (Student student stuArr) if (student.getIdNum() > max) { max = student.getIdNum(0; highestSoFar = student; } return highestSoFar; III: int maxPos = 0; for(int i = 1l i < stuArr.length; i++) if(stuArr[i].getIdNum() > stuArr[maxPos].getIdNum()) maxPos = i; return stuArr[maxPos];

II and III only

Consider the following declarations in the program to find the quantitity base exp. double base = <a double value> double exp = < double value> /* code to find power which equals base exp*/ Which is correct replacement for /* code to find power, which equals base exp*/? I: double power; Math m new Math(); power = m.pow(base, exp); II: double power; power = Math.pow(base.exp); III: int power; power = Math.pow(base, exp);

II only

The following code fragment is intended to find the smallest value in arr[0] . . . . arr[n-1], but does not work as intended /** Preconiditon: * -arr is an array, arr.length = n. * - arr[0]. . . . arr[n-1] initialized with integers. * Postconidition: min = smaller value in arr[0] . . . . arr[n-1]. */ int min = arr[0]l; int i = 1; while (i < n) { i++ if (arr[i] < min) min = arr[i]; } For the segment to work as intended which of the following modifications could be made? I Change the line int i = 1; to int i = 0; Make no other changes II: Change the body of the while loop to { if (arr[i] < min) min = arr[i]; i++ } Make no other changes III: Change the test for the while loop as follows while (i <= n) Make no other changes

II only

public class Address { private String name; private String street; private String city; private String state; private String zip; //constructors . . . . //accessors public String getName() { return name; } public String getStreet() {return street;} public String getCity() {return city;} public String getState() {return state;} public String getZip() {return zip;} } public class Student { private int idNum; private double gpa; private Address address; //constructors . . . //accessors public aDdress get Address() {return address; } public int getIdNum() {return idNum;} public double getGpa {return gpa} } The following code segment is to print out a list of addresses for (Address addr : list) { /* more code */ } Which is a correct replacement for /* more code */? I System.out.prtinln(list[i].getName()); System.out.println(list[i].getStreet()); System.out.print(list[i].getCity() + ", "); System.out.print(list[i].getState() + " "); System.out.println(list[i].getZip()); II: System.out.println(addr.getName()); System.out.printnln(addr.getStreet()); System.out.print(addr.getCity() + ", "); System.out.print(addr.getState() + " "); System.out.println(addr.getZip()); III: System.out.prtinln(addr);

II only

public class IntPair { private int firstValue; priavet int secondValue; public IntPair(int first, int second) { firstValue = first; secondValue = second; } public int getFirst() { return firstValue;} public int getSeoncd() { return secondValue; } public void setFirst(int a) { firstValue = a;} public void setSecond(int b) { secondValue = b;} } Consider the following program that uses the IntPair class public class TestSwap { public static void swap(IntPair pair) { int temp = pair.getFirst(); pair.setFirst(pair.getSecond()); pari.setSecond(temp); } public static void main (String[] args) { int x = 8, y -6; /* code to swap x and y */ } } Which is a correct replacement for /*code to swap x and y */? I: IntPair iPair = new IntPair(x, y); swap (x. y); x = iPair.getFirst(); y = iPair.getSecond(); II: IntPair iPair = new IntPair(x, y); swap (iPair); x = iPair.getFirst(); y = iPair.getSecond(); III: Int Pair iPair = new IntPair(x, y); swap(iPair); x = iPair.setFirst(); y = iPair.setSecond();

II only

Assuming that players as been declared as an array of BingoCard which replacement for /*construct each BingCard */ is correct?

III only

Refer to these declarations Integer k = new Integer(8); Integerm = new Integer(4); Which test(s) will generate a compile-time error? I: if (k ==m) . . . II: if (k.intValue() == m.intValue()) . . . . III: if ((k.intValue()).equls(m.intValue())) . . . .

III only

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } Which of the following will cause an error message? I: Date d1 = new DAte (8, 2, 1947); Date d2 = d1; II: Date d1 = null; Date d2 = d1; III: Date d = null; int x= d.year();

III only

public class IntPair { private int firstValue; priavet int secondValue; public IntPair(int first, int second) { firstValue = first; secondValue = second; } public int getFirst() { return firstValue;} public int getSeoncd() { return secondValue; } public void setFirst(int a) { firstValue = a;} public void setSecond(int b) { secondValue = b;} } Here are three different swap methods, each intended for use in a client program. I: public static void swap (int a, int b) { int temp = a; a =b; b = temp; } II: public static void swap(Integer obj_a, Integer obj_b) { Integer temp = new Integer(obj_a.intValue()); obj_a = obj_b; obj_b = temp; } III: public static void swap(IntPair pair) { int temp = pair.getFirst(); pair.setFirst(pair.getSecond()); pair.setSecond(temp); } When correctly used in a client program with appropriate parameters, which method will swap two integers, as intended?

III only

public class Position { /** row and col are both >= 0 except in the default * constructor where they are initialized to -1. */ private int row, col; public Position() //constructor { row = -1; col = -1; } public Position(int r, int c) { row = r; col = c; } /** Returns row of Position */ public int getRow() { return col;} /** Returns Position north of (up from) this position. */ public Position north() { return new Position (row -1, col); } //Similar methods south, east, and west . . . . /** Compares this Position ot another Postiion object. * Returns -1 (less than), 0 (equals), or 1 (greater than). */ public int compareTo(Position p) { if(this.getRow() < p.getRow() || this.getRow() == p.getRow() && this.getCol() M p.getCol()) return -1; if (this.getRow() > p.getRow() || this.getRow() == p.getRow() && this.getCol() > p.getCol()) return 1; return 0; //row and col both equal } /** Returns String form of Postiion */ public String toStirng() { return "(" + row + "," + col + ")"; } } public class PositionTest { public static void main(String[] args) { Position p1 = new Position(2, 3); Position p2 = new Postiion(4, 1); Position p3 = new Position (2, 3); //tests to compare positions . . . } } Which boolena expression about p1 and p3 is true? I: p1 == po3 II: p1. equals (p3) III: p1. compareTo(p3) ==0

III only

public class Time { private int hrs; private int mins; private int secs; public Time() { /* implementation not shown */} public Time (int h, int m, int s) { /* implementation not show */ } /** Resets time to hrs = h, mins = m, secs = s. */ public void resetTime(int h, int m, int s) { /* implementation not shown*/ } /** Advances time by one second. */ public void increment() {*/implementation not shown */} /** Returns true if this time equals t, false otherwise. */ public boolean equals (Time t) { /* implementation not shown */} /** Returns a String with the time in the form hrs: mins: secs */ public String toString() { /* implementation not shown */} } A client class has a display method that writes the time represented by its parameter: /** Outputs time t in the form hrs: mins: secs. */ public void display ( Time t) { /* method body */ } Which of the folloiwng are correct replacements for /* method body*/ ? I: Time T = new Time(h, m, s); II: System.out.pritnln(t.hrs + ";" + t.mins + ":" + t.secs); III: System.out.pritnln(t);

III only

Consider writing a program that reads the lines of any text file into a sequential list of lines. Which of the following is a good reason of any text file into a sequential list of lines. Which of the following is a good reason to implement the list with an array List of String objects rather than an array of String objects?

If any particular text file is unexpectedly long, the ArrayList will automatically be resized. The array, by contrast, may go out of bounds.

public class Position { /** row and col are both >= 0 except in the default * constructor where they are initialized to -1. */ private int row, col; public Position() //constructor { row = -1; col = -1; } public Position(int r, int c) { row = r; col = c; } /** Returns row of Position */ public int getRow() { return col;} /** Returns Position north of (up from) this position. */ public Position north() { return new Position (row -1, col); } //Similar methods south, east, and west . . . . /** Compares this Position ot another Postiion object. * Returns -1 (less than), 0 (equals), or 1 (greater than). */ public int compareTo(Position p) { if(this.getRow() < p.getRow() || this.getRow() == p.getRow() && this.getCol() M p.getCol()) return -1; if (this.getRow() > p.getRow() || this.getRow() == p.getRow() && this.getCol() > p.getCol()) return 1; return 0; //row and col both equal } /** Returns String form of Postiion */ public String toStirng() { return "(" + row + "," + col + ")"; } } public class PositionTest { public static void main(String[] args) { Position p1 = new Position(2, 3); Position p2 = new Postiion(4, 1); Position p3 = new Position (2, 3); //tests to compare positions . . . } } Which is true about the value of p1. compareTo(p2)?

It equals -1

Refer to method insert below /** Inserts element in its correct sorted position in list. * Precondition: list contain String values sorted * in decreasing order. */ public void insert (ArrayList<String> list, String element) { int index = 0; while (element.compareTo(list.get(index))) <0) index++; list.add(index. element); } Assuming that the type of element is compatible with the objects in the list, which is all true statement about the insert method?

It fails if element is smaller than the last item in list and works in all other cases

Which is true of the following boolean expression, given that x is a variable of type double? 3.0 == x * (3.0 / x)

It may evaluate to false for some values of x.

Consider this method public static String doSomething(String s) { final String BLANK = " "; //BLANK contains a single space String str = " "; //empty string String templ for (int i - 0; i < s.length(); i++) { temp = s.substring(i, i + 1); if (!(temp.equals(BLANK))) str += temp; } return str; } Which of the following is the most precise description of what doSomething does?

It returns a String that is equivalent to s with all its blanks removed.

public class Rational { private int numerator; private int denominator; /** default constructor */ Rational() { /*implementation not shown */} /** Constructs a Rational with numerator n and * denominator 1. */ Rational (int n) { /*implementation not shown */} /** Returns numerator. */ int numerator() { /* implementation not shown */} /** Returns denominator. */ int denominator() { /* implementation not shown */} /** Returns (this + r). Leaves this unchanged */ public Rational plus (Rational r) { /* implementation not shown */} //Similarly for times, minus, divide . . . /** Ensures denominator > 0. */ private void fixSigns() { /* implementation not shown */ } /** Ensures lowest terms. */ private void reduce() { /* implementation not shown*/ } } The constructors in the Rational class allow initialization of Rational object in several different way. Which of the following will cause an error?

Rational r4 = new Rational(3.5);

public class Rational { private int numerator; private int denominator; /** default constructor */ Rational() { /*implementation not shown */} /** Constructs a Rational with numerator n and * denominator 1. */ Rational (int n) { /*implementation not shown */} /** Returns numerator. */ int numerator() { /* implementation not shown */} /** Returns denominator. */ int denominator() { /* implementation not shown */} /** Returns (this + r). Leaves this unchanged */ public Rational plus (Rational r) { /* implementation not shown */} //Similarly for times, minus, divide . . . /** Ensures denominator > 0. */ private void fixSigns() { /* implementation not shown */ } /** Ensures lowest terms. */ private void reduce() { /* implementation not shown*/ } } Here is the implementation code for the plus method: /** Returns (this + r). Leaves this unchanged. */ public Rational plus(Rational r) { fixSigns(); r.fixSigns(); int denom = denominator * r.denominator; int numer = numerator * r.denominator + r.numerator * denominator; /* more code */ } Which of the following is a correct replacement for /* more code *?

Rational rat = new Rational (number, denom) rat. reduce(); return rat;

One of the rules for converting English to Pigs Latin states: If a words begins with a consonant, move the consonant to the end of the word and add "ay".Thus "dog" becomes "ogday," and "crisp" becomes "rispcay". Suppose s is a String containing an English word that begins with a consonant. Which of the following creates the correct corresponding word in Pig Latin? Assume the declarations

pigString = s.substring(1, s.length()) + s.substring(0, 1) + ayString;

Assume that a square matrix mat is defined by int [] [] mat = new int[SIZE] [SIZE] //SIZE is an integer constant >= 2 . . .. . You may assume the existence of this swap method /**Interchange mat[a][b] and mat [c] [d]. */ public void swap (int [] [] mat. int a, int b, int c, int d) What does the following code segment do?

Reflects mat through its minor diagonal. For example, - - - -

public class Address { private String name; private String street; private String city; private String state; private String zip; //constructors . . . . //accessors public String getName() { return name; } public String getStreet() {return street;} public String getCity() {return city;} public String getState() {return state;} public String getZip() {return zip;} } public class Student { private int idNum; private double gpa; private Address address; //constructors . . . //accessors public aDdress get Address() {return address; } public int getIdNum() {return idNum;} public double getGpa {return gpa} } A client method has the declaration, followed by code to initialize the list: Adress[] list = new Address[100]; Here is a code segment to generate a list of names only. for (Adress a: list) /* line of code*/ Which is a correct /* line of code*/?

System.out.println(a.getName());

public class Address { private String name; private String street; private String city; private String state; private String zip; //constructors . . . . //accessors public String getName() { return name; } public String getStreet() {return street;} public String getCity() {return city;} public String getState() {return state;} public String getZip() {return zip;} } public class Student { private int idNum; private double gpa; private Address address; //constructors . . . //accessors public aDdress get Address() {return address; } public int getIdNum() {return idNum;} public double getGpa {return gpa} } A client method has this declaration Student[] allStudents = new Student[NUM_STUDS]; //NUM_STUDS is //an in constant Here is a code segment to generate a list of Student names only (You may assume that allStudents has been initialized) for (Student student : allStudents) /* code to print list of names */ Which is a correct replacement for /* code to print list of names */?

System.out.println(student.getAddress().getName());

public class Time { private int hrs; private int mins; private int secs; public Time() { /* implementation not shown */} public Time (int h, int m, int s) { /* implementation not show */ } /** Resets time to hrs = h, mins = m, secs = s. */ public void resetTime(int h, int m, int s) { /* implementation not shown*/ } /** Advances time by one second. */ public void increment() {*/implementation not shown */} /** Returns true if this time equals t, false otherwise. */ public boolean equals (Time t) { /* implementation not shown */} /** Returns a String with the time in the form hrs: mins: secs */ public String toString() { /* implementation not shown */} } Which of the following is a false statement about the methods?

The Time class has three constructors.

Let x be a variable of type double that is positive. A program contains the boolean expression (Math.pow(x, 0.5) == Math.sqrt(x)). Even though x ^ 1/2 is mathematically equivalent square root of x, the above expression returns the value false in a student's program. Which of the following is most likely reason?

There is round-off error in calculating the pow and sqrt functions

Suppose it is necessary to keep a list of all ticket transactions. Assuming that there are NUMSALES transactions, a suitable declaration would be

Transaction[] listOfSales = new Transaction[NUMSALES];

public class Rational { private int numerator; private int denominator; /** default constructor */ Rational() { /*implementation not shown */} /** Constructs a Rational with numerator n and * denominator 1. */ Rational (int n) { /*implementation not shown */} /** Returns numerator. */ int numerator() { /* implementation not shown */} /** Returns denominator. */ int denominator() { /* implementation not shown */} /** Returns (this + r). Leaves this unchanged */ public Rational plus (Rational r) { /* implementation not shown */} //Similarly for times, minus, divide . . . /** Ensures denominator > 0. */ private void fixSigns() { /* implementation not shown */ } /** Ensures lowest terms. */ private void reduce() { /* implementation not shown*/ } } Assume these declarations: Rational a - new Rational(); Rational r = new Rational(numer, denom); int n - value; //numer, denom, and value are valid integer values Which of the following will cause a compile-time error?

a = n.plus(r);

Assume that a and b are integers. The boolean expression !(a <= b) && (a * b > 0) will always evaluate to true given that

a > b and b > 0.

Given that a, b, and c are integers, consider the boolean expression (a < b) || !((c == a * b) && ( c < a)) Which of the following will guarantee that the expression is true

c < a is false

Refer to the following code fragment: double answer = 13/5; System.out.println("13/5 =" + answer); The output is 13/5 =2.0; The programmer intends the output to be 13 / 5 = 2.6 Which of the following replacements for the first line of code will not fix the problem?

double answer = (double) (13/5);

Here is the getTotal method from the Purse class. /**Returns the total value of coins in purse.*/ public double getTotal() { double total = 0; /* more code*/ return total; } Which of the follwoing is a correct replacement for /*more code*/?

for (Coin c: coins) { total += c.getValue(); }

A simple Tic-Tac Toe board is 3 X 3 array filled with either X's, O's, or blanks. Here is a class or a game for Tic-Tac-Toe. public class TicTacToe { private String [][] board; private static final int ROWS = 3; private static final int COLS = 3; /** Construct an empty board. */ public TicTacToe() { board = new String[ROWS][COLS]: for(int r = 0; r < ROWS; r++) for(int c = 0; c < COLS; c++) BLAH BLAH BLAH public String toString() { String s = ""; //empty string / * more code */ return s; } } Which segment represents a correct replacement for /* more code */ for the toString method?

for (int r = 0; r < ROWS; r++) { s = s + "l"; for (int c = 0; c < COLS; c++_ s = s + board[r] [c]; s = s + "/\n"; }

Which represents correct /*code to calculate amount*/ in the totalPaid method?

for(Ticket t : tickList) total += t.getPrice();

Here are the private instance variables for a Frog object: public class Frog { private String species; private int age; private double weight; private Position position; //position (x, y) in pond private boolean amAlive; . . . . } Which of the following methods in the Frog class is the best candidate for being a static method?

getPondTemepreature //returns temperature of pond

public class Time { private int hrs; private int mins; private int secs; public Time() { /* implementation not shown */} public Time (int h, int m, int s) { /* implementation not show */ } /** Resets time to hrs = h, mins = m, secs = s. */ public void resetTime(int h, int m, int s) { /* implementation not shown*/ } /** Advances time by one second. */ public void increment() {*/implementation not shown */} /** Returns true if this time equals t, false otherwise. */ public boolean equals (Time t) { /* implementation not shown */} /** Returns a String with the time in the form hrs: mins: secs */ public String toString() { /* implementation not shown */} } Which of the following represents correct implementation code for the constructor with parameters?

hrs = h; mins = m; secs = s;

public class Temperature { private String scale //valid values are "F" or "C" private double degrees; /** constructor with specified degrees and scale */ public Temperature( double tempDegrees, String tempScale) { /*implementation not shown */ } /**Mutator. Converts this Temperature to degrees Fahrenheit. * Returns this temperature in degrees Fahrenheit. * Precondition: Temperature is a valid temperature * in degrees Celsius. */ public Temperature toFahrenheit() { /* implementation not shown */} /**Mutator. Converts this Temperature to degrees Celsius. *D Returns this temperature in degrees Celsius. * Precondition: Temperature is a valid temperature * in degrees Fahrenheit. */ public Temperature toCelsius() { /* implementation not shown */} /** Mutator * Returns this temperature raised by amt degrees. */ public Temperature lower (double amt) { /*implementation not shown */} /** Returns true if tempDegrees is a valid temperature * in the given temperature scale, false otherwise. */ public static boolean is ValidTemp(double tempDegrees, String tempDegrees, String tempScale) { /* implementation not shown */} //Other methods are not shown } Consider the following code: public class TempTest { public static void main(String[] args) { System.out.pritnln("Enter temperature scale: "); String tempScale = . . . ; //read user input System.out.println("Enter number of degrees: "); double tempDegrees = . . . ; //read user input /* code to construct a valid temperature from user input */ } } Which is the best replacement for /*code to construct . . . */?

if (Temeprature.isValidTemp(tempDegrees, tempScale)) Temperature t - new Temperature (tempDegrees, tempScale); else /*error message and exit program */

Here are some examples of negative numbers rounded to the nearest integer: Negative real number -3.5 -8.97 -5.0 -2.487 -0.2 Rounded to nearest integer: -4 -9 -5 -2 0 Refer to the following deceleration double d = -4.67; Which of the following correctly rounds d to the nearest integer?

int rounded = (int) (d- 0/5);

A program simulates 50 slips of paper, numbered 1 through 50, placed in a bowl for a raffle drawing. Which of the following statements sores in winner a random integer from 1 to 50?

int winner = (int) (Math.random() * 50) + 1;

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } A client program creates a Date object as follows: Date d= new Date(1, 13, 2002); Which of the following subsequent code segments will cause an error?

int y = d.year;

Consider this program segment for (int i = 2; i <= k; i++) if (arr[i] < someValue) System.out.print("SMALL"); What is the maximum number of time that SMALL can be printed?

k - 1

Let list be an ArrayList<Integer. containing theses elements 2 5 7 6 0 1 Which of the following statements would not cause an error to occur? Assume that each statement applies to given list, independent of the other statements

list.add(6,9)

/** Returns true if the 4-digit integer n is valid, * false otherwise */ boolean checkNumber(int n) { int d1, d2, d3, checkDigit, nRemaining, rem; //strip off digits checkDigit = n % 10; nRemaining = n / 10; d3 = nRemaining % 10; nRemaining /= 10; d2 = nRemaining % 10; nRemaining /= 10; d1 = nRemamining % 10; //check validity rem = (d1 + d2 + d3) % 7; return rem == checkDigit; } A program invokes method checkNumber with the statment boolean valid = checkNumber(num); What is the purpose of the local variable nRemaining?

nRemaining enhances the readability of the algorithm

public class Date { private int day; private int month; private int year; public Date () //default constructor { . . . } public Date (int mo, int da, int yr) //constructor { . . . } public int month() //returns month of Date { . . . } public int day() //returns day of Date { . . . } public int year() //returns year of Date { . . . } //Returns String representation of Date as " m/d/y", e.g/ 4/18/1985 public String toString() { . . . } } The Date class is modified by adding the following mutator method: public void addYears (int n) //add n years to date Here is part of the poorly coded client program that uses the Date class: public static void addCentury(Date recent, Date old) { old.addYears(100); recent = old; } public static void main(string[] args) { Date oldDate = new Date(1, 13, 1900); Date recentDate = null; addCentury(recentDate, oldDate); . . . } Which will be true after executing this code?

recentDate is a null reference

Consider the following code segment if (n != 0 && x / n > 100) statement 1 else statement 2 - - - if n i s of type int and has a value of 0 when the segment is executed, what will happen?

statement2, but not statement1, will be executed

Consider these declarations ArrayList,Strings> strList = new ArrayList,String>(); String ch = " "; Integer intOb = new Integer(5); Which statement will cause an error?

strList.add(intOb + 8);

public class Rational { private int numerator; private int denominator; /** default constructor */ Rational() { /*implementation not shown */} /** Constructs a Rational with numerator n and * denominator 1. */ Rational (int n) { /*implementation not shown */} /** Returns numerator. */ int numerator() { /* implementation not shown */} /** Returns denominator. */ int denominator() { /* implementation not shown */} /** Returns (this + r). Leaves this unchanged */ public Rational plus (Rational r) { /* implementation not shown */} //Similarly for times, minus, divide . . . /** Ensures denominator > 0. */ private void fixSigns() { /* implementation not shown */ } /** Ensures lowest terms. */ private void reduce() { /* implementation not shown*/ } } The method reduce() is not a public method because

the reduce() method is not intended for use by objects outside the Rational class

Refer to method match below /** Returns true if there is an integer k that occurs * in both arrays; otherwise returns false * Precondition * - v is an array of int sorted in increasing order * - w is an array of int sorted in increasing order *-N is the number of elements in array v * -M is the number ofelemnts in array w * - v[0] . . . v[N-1] and w[0] . . . w[M-1] is initialized with integers. * -V[0] < v[1] < . . . < v[N-1] and w[0] < w[1] < . . <w{M-1]. */ public static boolean match(int[] v, int[] w, int N, int M) . . . . . . . . . .. . . Assuming that the method has not been exited which assertion is true at the end of every execution of the while loop?

v[0]. . v[vIndex-1]j and w[0] . . . w[wIndex-1] contain no common value

What values are stored in x and y after execution of the following program segment? int x = 30, y = 40; if (x >= 0) { if (x <= 100) { y = x * 3; if (y < 50) x /= 10; } else y = x * 2; } else y = -x

x = 30 y = 90


Kaugnay na mga set ng pag-aaral

Chapter 4: Structured Cabling and Networking Elements

View Set

Science Chapter 7 water lesson 1

View Set