Exam #3 (Fall 2018) Flashcards
What is the output for the following code fragment?
int k = 1, m = 1; while (k <= 1) { while(m <= 1) { if (m == 1 ) { break; } m++; } System.out.println("Hi"); k++; } System.out.println("Done");
Hi
Done
Appending (concatenating) strings is:
a. An expensive operation and an alternative (e.g., StringBuffer) should be used.
b. A cheap operation.
c. An operation that have the same performance as using a StringBuffer.
d. None of the above.
a. An expensive operation and an alternative (e.g., StringBuffer) should be used.
When we execute the following code:
System.out.println(3.9 - 3.8 == .10);
a. We will always get true.
b. Getting false is possible as some numbers cannot be represented precisely in binary.
c. An exemption will be thrown.
d. None of the above.
b. Getting false is possible as some numbers cannot be represented precisely in binary.
When an exception occurs, Java pops back up the call stack to each of the calling methods to see whether the exception is being handled in a catch block of the method.
True or False.
True
In a JUnit test method if you don’t provide an assertion the test is considered to have succeeded.
True or False.
True
Creating an array of size 0 is not allowed in Java.
True or False.
True
The code in the finally block is executed:
a. Only when no exemption takes place.
b. Always
c. Only when the exemption takes place.
d. None of the above.
b. Always
The following class has a privacy leak. Fix the code to remove it (feel free to edit and cross out the code provided).
public class Example { private StringBuffer data; public Example(String dataIn) { data = new StringBuffer(); data.append(dataIn); } public StringBuffer getData() { return data; } }
getData method will return a copy of data
We have an array of string objects and we would like to make a copy of the array so changes to the new array will not affect the original. To make the copy:
a. We need to make a deep copy, otherwise changes in the new array will affect the original.
b. A shallow copy where we only duplicate the array object and not the string objects is enough.
c. A reference copy is enough.
d. None of the above.
b. A shallow copy where we only duplicate the array object and not the string objects is enough.
Math.random() returns a value between 0 (inclusive) and less than 1. Complete the following assignment so x is assigned a random integer value between 1(inclusive) and 100 (inclusive). The only function you can use is Math.random().
int x =
(int)(Math.random() * 100) + 1;
Rewrite the following code fragment by replacing the if statement with the ternary (? : ) operator.
/* Original Code */ String name; int y = scanner.nextInt(); if (y > 0) { name = "Pos"; } else { name = "Neg"; }
/* Rewritten Code */
String name;
int y = scanner.nextInt();
name =
name = y > 0 ? “Pos” : “Neg”;