Exam Questions Flashcards
Which access modifier should you use here to give access of the String field to class B but NOT to class C?
// filename: A.java
package foo;
public class A {
____ String s = “hello”;
}
// filename: B.java
package bar;
public class B extends A {
}
// filename: C.java
package bar;
public class C {}
Protected
How many different objects and reference variables are created in the following code?
public void createObjects() {
Object o1 = new Object();
Object o2 = o1;
Object o3 = new Object();
o3 = o1;
}
2 objects, 3 reference variables
What Type of Polymorphism is shown below?
public class Example {
public void doStuff() { System.out.println(“hello”); }
public void doStuff(int x) { System.out.println(x); }
}
Method Overloading
Which code snippet will allow for the following object instantiation?
Example myExample = new Example(“foo”);
public class Example {
public String name;
public Example(String s) {
this.name = s;
}
}
What is the output of the following code snippet?
String[] arr = {“foo”, “bar”, “foobar”, “baz”};
for (int i = 0; i < arr.length; i++) {
if (i > 1 && arr[i].length() > 3) {
System.out.println(arr[i]);
}
}
foobar
Identify the correct output for the following code snippet.
public class Example {
public static int countStatic = 0;
public int count = 0;
public static void main(String[] args) {
Example e1 = new Example();
Example e2 = new Example();
e1.increment();
e2.increment();
System.out.println(e1.count);
System.out.println(e2.count);
System.out.println(countStatic);
}
public void increment() {
count++;
countStatic++;
}
}
1
1
2
What is the output for the following code? Why?
String s1 = “hello”;
String s2 = “ world”;
s1.concat(s2);
System.out.println(s1);
String s3 = s1.concat(s2);
System.out.println(s3);
hello
hello world
Strings are immutable, therefore calling “concat” does not modify the string, but returns a new string.
How would you evaluate the following assertions based on the code below?
Can variable x be used at A? Why or why not?
Can variable y be used at B? Why or why not?
public class Scopes {
public void doStuff() {
int x = 1;
for (int i=0; i < 5; i++) {
int y = 1;
// A
}
// B
}
}
x CAN be used at A because the block scope is within the method scope and variables from an enclosing scope can always be accessed. y CANNOT be used at B because variables in block scope cannot be accessed outside of the block.
Identify the proper use of the interface declared in the code below.
public interface Driveable {
public void drive();
}
public class Car implements Driveable {
public void drive() {
System.out.println(“driving the car…”);
}
}
What is the output of this code when an exception is thrown at A?
public class ExceptionExample {
public void mayThrowException() {
try {
riskyCode(); // A
System.out.println(“after A”);
} catch(Exception e) {
System.err.println(“Uh oh - something went wrong!”);
} finally {
System.out.println(“finally block”);
}
System.out.println(“continuing…”);
}
}
Uh oh - something went wrong!
finally block
continuing…
What would be the best collection to use in the code below, if we want to ensure that no name appears twice when we print them out?
_____<String> names = getNames();
names.add("Bob");
names.add("Julie");
for (String name : names) {
System.out.println(name);
}
(assume "getNames()" returns the correct collection of names)</String>
Set
Identify the correct type of data structure to use in the code below.
____<String, Integer> countOfWords = getCounts();
Set<String> keys = countOfWords.keySet();
for (String k : keys) {
System.out.println(countOfWords.get(k));
}</String>
Map
Identify ALL of the Java or OOP concepts being used in the code snippet below. (select all that apply)
Generics
Polymorphism
Casting
Constructor
Wrapper Class
List<Integer> mylist = new ArrayList<>();</Integer>
Generics
Polymorphism
Constructor
Wrapper Class
Fill in the blank to complete the JUnit test below.
public class Addition {
public int methodToTest(int x, int y) {
return x + y;
}
}
public class AdditionTest {
@Test
public void testAddPositiveInts() {
int n = 2;
int m = 3;
_______________________________
}
}
Assert.assertEquals(5, methodToTest(n,m));
True/False
Checked exceptions must ALWAYS be caught in a try-catch block.
False
What is correct about checked exceptions? (select all that apply)
Checked Exceptions are the same as errors.
Checked exceptions are checked at compile time.
Checked exceptions should be handled.
Checked exceptions come from the programmer writing bad code and should be fixed by the programmer .
Checked exceptions are checked at compile time.
Checked exceptions should be handled.
T/F
A try block must have a catch block.
False
Which is true about arrays in Java?
Arrays are dynamic and can change size by adding elements.
Arrays have a fixed size and cannot grow or shrink.
Arrays are a primitive data type.
Arrays are immutable, so elements inserted into an array cannot be changed in any way.
Arrays have a fixed size and cannot grow or shrink.
Which use of the final keyword will lead to compilation errors?
public final class Example {
public final void foo() {
final int x = 4;
final int y = 3;
y++;
System.out.println(x*y);
}
}
on the variable y
Which series of commands compiles and then runs the program “Hello.java”?
javac Hello.java
java Hello
Match the variable scopes for each given variable in the code snippet below.
public class Greetings {
static String w = ‘welcome’;
String x = 'hello'; void speak() { String y = 'hi'; for (int z=0; z < 4; z++) { System.out.println(z); } } }
w Static/class scope
x Instance scope
y Method scope
z Block scope
T/F
The following code snippet is how we create a class in Java.
public void buildString(String start, String add) {
String toBuild = start;
for(int i=0; i < 100; i++) {
toBuild.concat(add);
}
System.out.println(toBuild);
}
False
T/F
You could use static variables if you want all instances of a class to have a variable with a shared value across all instances of the same class.
True
Assume that a, b, and c refer to instances of wrapper classes. Which of the following statements are correct?
a.equals(a) will always return true.
b.equals(c) may return false even if c.equals(b) returns true.
a.equals(b) returns same as a == b.
a.equals(b) returns false if they refer to instances of different classes.
a.equals(a) will always return true.
a.equals(b) returns false if they refer to instances of different classes.
Which of the following statements is correct about Abstract Classes? (select all that apply))
A concrete class can have multiple Abstract classes inherited.
In order to inherit an abstract class when using a concrete class, we can use the keyword extends.
An abstract class cannot have any concrete methods predefined.
An abstract class does not need to have any predefined methods.
In order to inherit an abstract class when using a concrete class, we can use the keyword extends.
An abstract class does not need to have any predefined methods.
Which of the following is NOT a command in the DDL sublanguage of SQL?
CREATE
DELETE
ALTER
DROP
TRUNCATE
DELETE
Which of the following is NOT a command in the DML sublanguage of SQL?
INSERT INTO
UPDATE
DELETE
QUERY
QUERY
Identify the correct syntax to retrieve all attributes of the employees table who have a salary over $50k and do not work in Sales:
EMPLOYEES
ID Name Salary Dept
SELECT * FROM employees WHERE salary > 50000 AND dept != “Sales”;
Which of the following are used in the Data Access Object design pattern:
Abstraction via interfaces
Singleton pattern via private constructor
Polymorphism via method overloading
Recursion
Abstraction via interfaces
What is the difference between the simple and prepared statement?
Connection conn = getConnection();
String userInput = getInput();
Statement st = conn.createStatement();
st.executeQuery(“SELECT * FROM “ + userInput);
PreparedStatement ps = conn.prepareStatement(“SELECT * FROM ?”);
ps.setString(1, userInput);
ps.executeQuery();
The PreparedStatement prevents SQL injection by parameterizing and pre-compiling the query string.
Select the operations which are a part of DDL:
SELECT
CREATE
ALTER
UPDATE
TRUNCATE
DROP
CREATE
ALTER
TRUNCATE
DROP
The UPDATE operation is categorized under which SQL sublanguage?
DML
In the statement “SELECT * FROM users” what’s the * referring to?
Columns
What is the difference between INNER JOIN and OUTER JOIN?
Inner join will return only the rows that match based on the join predicate
In SQL, which JOIN will return the matching rows plus the ones that are null in the first table?
Right Join
T/F
DriverManager is the first interface you need to use in order to set up JDBC functionality.
False
Which JDBC Interface is used to create an instance of a Statement?
Connection
What is the purpose of a ResultSet?
To use data retrieved from the database
Which of the following assertions about CHAR and VARCHAR are incorrect? (select two)
Strings inserted into a CHAR column will be padded, while strings inserted into a VARCHAR column will not be.
CHAR is fixed in length and VARCHAR is variable length.
CHAR and VARCHAR can be converted between each other with no problem.
A length must be defined for CHAR and VARCHAR columns.
CHAR and VARCHAR can be converted between each other with no problem.
A length must be defined for CHAR and VARCHAR columns.
A column marked PRIMARY KEY is implicitly (select all that apply):
unique
final
serial
foreign key
not null
default
Unique
Not Null
Which of the following terms is used to describe records in a database?
Rows
Columns
Attributes
Properties
Rows
Which of the following is NOT considered part of a database’s schema?
Tables
Columns
Table Relationships
Rows
Rows
I would like to design a REST API so that users can send data like this to my books API to create a new book:
{
“ISBN”: 182037184371,
“Title”: “Adventures of Huckleberry Finn”,
“Author”: “Mark Twain”
}
What kind of HTTP method should be used for this kind of request, and where would this data be found in the request?
Use a POST request, data should be in the body
This is an HTTP response received from a server. What does this mean?
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: text/html
<html>
<body>
<h1>Hello World</h1>
<body>
</html>
</body></body></html>
The request was completed successfully and the server returned an HTML page to the client
What, if anything, is wrong with this endpoint when designing a REST API?
mylibrarydemo.com/api/getAllBooks
RESTful endpoints should refer to nouns, not verbs. The HTTP method in the request should instead specify the action to be taken.
What does this HTTP response mean that was returned from a server?
HTTP/1.1 404 Not Found
Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body>
</html>
There was a client side error
Match the HTTP verbs to their proper usage in a RESTful API
GET
POST
PUT
DELETE
GET: Retrieves a representation of a resource
POST: Adds a resource
PUT: Updates a resource
DELETE: Removes a resource
Identify the correct series of commands to:
1) Go to the “main” branch
2) See the current state of the files in the branch
3) Make a change
4) Update the remote repository
git checkout main; git status; git add; git commit; git push
Which of the following does NOT describe git?
It is a version control software for source code
Unlike subversion or mercurial, git is designed to be distributed instead of centralized
Git is short for “Github”
The units of work that are tracked in git are called commits
Git is short for “Github”
What is Git?
A Version Control System
What are some differences between a LinkedList and an ArrayList? Choose all that are correct
A LinkedList and an ArrayList both only implement the List interface
An ArrayList is the same as a LinkedList
A LinkedList has nodes with pointers to the next node
A LinkedList has faster insertion and deletion time than an ArrayList
A LinkedList has nodes with pointers to the next node
A LinkedList has faster insertion and deletion time than an ArrayList
T/F
HashSet is Sorted
False
If I add 3 of the same exact object to a HashSet, how many will be stored?
If I add 3 of the same exact object to a HashSet, how many will be stored?
1
The correct definition for Queue?
A Collection interface that holds & processes elements in FIFO (first in, first out) order.
What is the Scanner class used for?
Parsing input from text into primitives and strings, from a File or InputStream
Which of the following is the correct lambda expression which adds two numbers and returns their sum?
(int a, int b) -> { return a + b;};
(a, b) -> {return a + b;};
Both of the above.
None of the above.
Both:
(int a, int b) -> { return a + b;};
(a, b) -> {return a + b;};
T/F
The Map interface defines an iterator() method.
False
What does NOT belong in the Java Heap?
Static variables
Objects
String Pool
Methods
Methods
Which of the following is not a Wrapper Class
Boolean.
Long.
Double.
Short.
All of these are Wrapper classes.
All of these are Wrapper classes.
T/F
You can assign a variable of a larger capacity to a smaller variable without casting.
False