Week 3 + Week 2 and 1 Review Flashcards
What is a generic type?
A generic class or interface that is parameterized over types.
Why use Generics?
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.
Two types of generics? What does each do?
Generic method - introduce their own type parameters.
Generic class -
What is a generic method?
Exactly like a normal method but a generic method has type parameters that are cited by actual type.
Benefits of generic code over non-generic?
- Stronger type checks at compile time. A java compiler applies strong type checking to generic code and issues errors if the code violates type safety.
- Elimination of casts.
What are generics commonly used with?
Collections.
What is a generic called when declared on a class?
Generic type.
Why are generics useful?
Because it can help you to restrict a class to only accept objects of a given type and the compiler will prevent you from using any other type.
Why would the following code benefit from generics? How would you implement that code?
List names = new ArrayList();
names. add(“Alice”);
name. add(new Object());
In this code you would have to hope that other developers would know to use a certain data type. Generics would make it so the developer can only use objects of a given type.
List names = new ArrayList<>();
names. add(“Alice”);
names. add(new Object());
What is the Collections Framework?
A set of classes and interfaces that implement commonly used data structures.
What is a collection?
A single object which acts as a container for other objects.
Are collections iterable?
yes.
Main difference between Collection and Map?
Collection’s are iterable, maps are not.
Three interfaces derived from the Collection interface?
List.
Queue.
Set.
Classes derived from the List interface?
ArrayList.
Vector.
LinkedList.
Classes derived from the Queue interface?
LinkedList.
Priority Queue.
Classes derived from the Set interface?
Hash Set.
Linked Hash Set.
What is a List in Java?
A collection that is ordered and preserves the ordered in which elements are inserted into the list.
What is a Vector?
An older class which implements List.
A thread safe implementation of an ArrayList.
Vector.
What should you use for implementing a stack?
ArrayDeque.
ArrayList(class) implements _______ which extends _______.
List (interface)
Collection
Set Extends _______ which Extends ________ which Implements ________.
Sorted Set.
Navigable Set.
Treeset.
What is the Set interface?
an unordered collection of objects in which duplicate values cannot be stored.
How can I make the following code generic?
public class Printer { }
Add the type parameter after the class name.
public class Printer { }
How can I make the following code print an Integer generic type, assume Printer is generic.
Printer printer = new Printer (5);
printer.print();
You need to specify the type.
Printer printer = new Printer<>(5);
printer.print();
Generics work with primitive types and wrapper class objects.
False. Generics don’t work with primitive types.
Find the error in the following code.
Printer doublePrinter = new Printer<>(“Hello”);
doublePrinter.print();
The generic type is asking for a double (), but we attempted to print out a string ( (“Hello”) ).
Where is the error in the following code?
ArrayList cats = new ArrayList<>();
cats. add(new Cat());
cats. add(new Dog());
The ArrayList which is set to is trying to add Dog.
Which package is List found in?
java.util
Which interface does List inherit?
Collection
What are the four implementation classes of List interface?
ArrayList.
LinkedList.
Stack.
Vector.
Declare an array of the names of 4 friends. Call it friendsArray.
String[] friendsArray = new String[4];
Declare an array of your friends with the names… John, Steph, Sam, Amy. Call it friendsArray
String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};
Declare an ArrayList with reference name friendsArrayList.
ArrayList friendsArrayList = new ArrayList<>();
What is the import for ArrayList?
java.util.ArrayList
Which have a fixed size, Array or ArrayList? or neither? or Both?
Array’s have a fixed size.
Declare an ArrayList called friendsArrayList that holds the values John, Chris, Eric, and Luke.
ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));
How can you print out “Steph” from the Array?
String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};
System.out.println(friendsArray[1]);
How can you print out “Eric” from the following:
ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));
System.out.println(friendsArrayList.get(2));
How would I get the length of an Array called friendsArray? Show code.
System.out.println(friendsArray.length);
How would I get the length of an ArrayList called friendsArrayList? Show code.
System.out.println(friendsArrayList.size());
how would I add string “Mitch” to an ArrayList called friendsArrayList?
friendsArrayList.add(“Mitch”);
How would I change the first value in an Array called friendsArray to “Carl”?
friendsArray[0] = “Carl”;
How would I change the first value in an ArrayList called friendsArrayList to “Carl”?
friendsArrayList.set(0, “Carl”);
How would I remove “Chris” from an ArrayList called friendsArrayList?
friendsArrayList.remove(“Chris”);
implement a class called multiThreadThing, which extends thread, in your main method and run two threads. Threads will be called myThing and myThing2
public static void main(String[] args) {
multiThreadThing myThing = new multiThreadThing(); multiThreadThing myThing2 = new multiThreadThing();
myThing.start();
myThing2.start();
Explain the following code.
for(int i = 0; i < 5; i++)
This is a for loop that starts from count 0 (i =0) and iterates through the loop (i++) until i is no longer less than 5 (i<5)
Which package are Maps in ?
java.util package
What is a map?
An interface that represents a mapping between a key and a value.
how would a maps interface apply to managers and employees relationship?
You can map managers and employees with Managers (Key) with a list of Employees(Value) being managed.
Can you create objects in an interface? if so, how would you do it? If not, what do you need?
No.
You need a class that extends the interface.
Identify the problem and fix the code, show solution:
public class Dog {
private String name;
private int age;
public void setName (String name) {
name = name;
name = name is setting the passed in String name to itself. So we need to add this. keyword.
public void setName(String name) {
this.name = name;
This will set this.name to the private String name, and set that to the String parameter in setName.
Identify the problem and fix the code, show solution:
public class Dog {
private String name;
private int age;
public void setName (String name) {
name = name;
name = name is setting the passed in String name to itself. So we need to add this. keyword.
public void setName(String name) {
this.name = name;
This will set this.name to the private String name, and set that to the String parameter in setName.
A constructor requires a return type? T/F?
False. a constructur can NOT have a return type.
Code the following:
class Main
main method
Create method called myMethod, pass through String name.
print out name in method.
call names Tom and Jim through myMethod in main Method.

What would I use if i wanted to iterate over a data structure?
for loop
count from 1-5 using a for loop.
for (int i = 0; i <= 5; i++)
System.out.println(i);
count from 1-5 using a while loop.
i = 1;
while (i <=5) {
System.out.println(i);
i++;
import a Scanner.
import java.util.Scanner
create a Scanner object called scan.
Scanner scan = new Scanner(System.in);
What is java type casting? Two types.
When you assign a value of one primitive data type to another type.
Wide (automatically)
narrow (manually)
When do I need to use casting?
When passing a smaller size type into a larger type size.
Cast the following code: go from double to int. name int variable ‘y’
double x = 9.5;
int y = (int) x;
Write code that manually boxes the following code. Name variable y.
double x = 5;
double y = new Double(x);
What are the two types of constructors?
No args.
Parameterized.
take a class called myClass and create a no args constructor from int num. set equal to 100.
public class myClass { int num; myClass() { num = 100; } }
Add a paramterized constructor to the following code:
class myClass { int x = 5;
myClass(int i) {
x = i
What is an access modifier? List them, and state their access level.
keyword which define the ability of other code to access the given entity.
public - available anywhere
protected - within the same package. and within same class.
default - within same package.
private - only within same class.
If i use the private access modifier, what will use to retrieve and change information within a private modifier.
Getters and Setters.
What is method overloading?
a feature that allows a class to have more than one method having the same name, if their parameters are different.
What is method overriding?
feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
Write code to exemplify overriding with the following:
class Parent
method show
class Child which inherits Parent
override method show
main method to print show.

What is an abstract class?
A class that you can NOT instantiate.
How do you create an abstract class? show code in example of public class called Animal.
public abstract class Animal {
}
What is an abstract method?
A method within an abstract class.
What’s the difference betwen an abstract class and an interface?
You can implement as many interfaces as you want but you can only extend one class.
And every field declared inside an interface is static and final.
Name all non-access modifiers.
static.
final.
abstract.
synchornized.
transient.
volatile.
strictfp.
What is unit testing?
what are the benefits of unit testing?
- A unit test is a program that exercises a small piece of the codebase in complete isolation.
- fast. unit tests don’t interact with elements external to the code such as databases, filesystems, or the network.
- Deterministic. If a given test is failing, it will continue to fail until a change is made to the test or the code.
Why is unit testing useful?
Unit testing can reduce bugs. Even if your code is technically correct, it might not do what you intend. That’s where testing is useful.
What is TDD?
test driven development. This is when you use tests to drive the development of the application.
3 steps to Workflow of TDD?
- Start by writing a unit test related to the feature you want to implement.
- Make the test pass by writing the lease possible amount of code.
- Refactor in order to get rid of duplication or other problems (optional).
What does JUnit Annotations @Test do?
declares a method as a test method.
What does JUnit Anootation @BeforeClass do?
declares a setup method that runs once, before all other methods in the class.
What does JUnit Annotation @Before do?
decalres a setup method that runs before each test method.
What does JUnit annotations @After do?
declares a tear-down method that runs before each test method.
What does JUnit Annotations @AfterClass do?
Declares a tear-dpwn method that runs once, after all other methods in the class.
Difference between checked and unchecked exception?
- Checked Exceptions are required to be handled or declared by the programmer.
- Unchecked Exceptions is not required to be handled or declared.
What is an exception in java?
an unwanted or unexpected event.
When an exceptions occurrs within a method, it creates an ______. This is called an ________.
object.
exception object.
What does the exception object contain?
Information about the exception such as the name and description of the exception and the state of the program when the exception occurred.
Error vs Exception. What’s the difference?
- An error indicatesa a serious problem that a reasonable application should not try to catch.
- An exception indicates conditions that a reasonable application might try to catch.
What is a try/catch block used for?
to handle exceptions that could be thrown in our application.
explain the two functions of the try/catch block.
The try block enclose the code that may throw an exception .
The catch block defines an exception to catch and runs the code inside only if that type of exeption is thrown.
What is a HashMap?
A map which:
stores elements in key-value pairs.
Insertion/Retrieval of element by key is fat.
Does not maintain order of insertion.
How to access a value in the HashMap? show example if I wanted to get the String “England” from an object called capitalCities.
Use get() method.
capitalCities.get(“England”)
Declare a HashMap called capitalCities. Put two Strings, the first being the country then the capital. Do with the following then print.
England, London
Berling, Germany
Washington DC, USA
HashMap capitalCities = new HashMap();
capitalCities.put(“England”, “London);
capitalCities.put(“USA”, “Washington DC”);
capitalCities.put(“Germany”, “Berlin”);
System.out.println(capitalCities);
which package is LinkedList in?
java.util
Create a linked list with the following:
class Main
main method
Linked list animals
elements in list include Dog, Cat, Cow
print out Linked List.
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList animals = new LinkedList<>();
animals. add(“Dog”);
animals. add(“Cat”);
animals. add(“Cow”);
System.out.println(“LinkedList: “ + animals);
}
}
What is an ArrayDeque?
A special kind of growable array that allows us to add or remove an element from both sides.
Which two itnerfaces does an arraydeque implement? Explain each.
Queue Interface: Interface that is a FIFO data structure where the elements are added from the back.
Deque Interface: A doubly ended Queue in which you can insert elements from both sides.
Write a line of code that would retrieve the first element from an Array Deque called animals.
Call it firstElement.
String firstElement = animals.getFirst()
Code an Array Deque with the following information:
class is Main
main method
insert Dog and Horse at the end of the array deque
insert cat at the beginning of the array deque.
print.

Create a priority queue with the following:
class Main
main method
call priority queue pQueue
add 10, 20, and 15 to pQueue
print out pQueue
print out the top element
print out the top elemenet and remove from container
print out top element again

Create a tree set with the following:
class Main
main method
create tree set called tsOne
add “A”, “B”, and “C” to the tree set

Declare a two dimensional array of ints
int [] []
create a two dimensional array that holds 200 elements with 10 in one array and 20 in another. call the array x.
int [] [] x = new int[10][20]
What does an iterator interface do?
allows us to access elements of the collection and is used to iterate over the elements in the collection(Map,List, or Set).
create an array list and iterate through the list to print out the values. Use the following:
imports
class Main
main method
ArrayList for cars and add Volvo, BMW, Ford, Mazda
Iterate through and print each.

which package is comparable interface found in?
java.lang
Write code that sorts integers in an array with the following:
class Main
main method
array containing 11,55,22,0,89. Then have program sort them from least to greatest.
print out sorted array.

What is garbage collection in java?
process by which java programs perform automatic memory management.
What is the StringBuilder class?
What is the difference between a StringBuilder and StringBuffer?
- A class used to create mutable (modifiable) strings.
- they are the same except that StringBuilder is non-synchronized.
What does the constructor, StringBuilder(), do?
It creates an empty String Builder with intial capacity of 16.
What does the constructor, StringBuilder(String str), do?
It creates a String Builder with a specified string.
What does the constructor, StringBuilder(int length), do?
It creates an empty String Builder with the specified capacity as length.
Explain the following code:
class Driver{
public static void main(String args[]){
StringBuilder sb=new StringBuilder(“Hello “);
sb.append(“Java”);
System.out.println(sb);
This creates a StringBuilder called sb and assigns “Hello” to it.
Then it changes sb to “Java” using the append method.
Explain the following String Builder methods:
append()
insert()
replace()
- append() method changes a String Builder argument with a given string.
- insert() method inserts a string inside a given position in the original string.
- replace() method replace a given string from a specified begin and end index.
what is a String Buffer? How is it different than a String Builder?
A String Buffer is a string that can be modified.
A String Buffer is synchronized, unlike a String Builder. This means that String Buffer is useful in multi-threading cases.
Explain the following String Buffer constructors:
StringBuffer()
StringBuffer(CharSequence seq)
StringBuffer(int capacity)
StringBuffer(String str)
- StringBuffer() constructs a string buffer with no charafcters in it and an initial capcacity of 16 characters.
- StringBuffer(CharSequence seq) constructs a string buffer that contains the same characters as the specified CharSequence.
- StringBuffer(int capacity) constructs a string buffer with no characters in it and the specified initial capacity.
- StringBuffer(String str) constructs a string buffer initiailized to the contents of the specified string.
What is a java runnable interface? What is the most common use?
an interface used to execute code on a concurrent thread.
Most common use is when we want only to override the run method.
import Thread class package.
import java.lang.Thread;
Two ways to create a Thread.
extending the Thread class and overriding the run() method.
OR implement Runnable interface.
created a Thread through extension using the following:
class Main
print out “This is a thread”
use a run() method.

What are the 6 thread states?
New.
Runnable.
Blocked.
Waiting.
Time Waiting.
Terminated.
Explain the New Thread state.
This is when a new thread is created. The thread has not yet started to run when the thread is in this state.
Explain runnable Thread State.
A thread that is ready to run is moved to a runnable state. In this state, a thread might be running or it might be ready to run at any time.
Explain blocked/waiting Thread state.
When a thread is temporarily inactive it is either blocked or waiting.
Explain the Timed waiting State
A thread is in timed waiting state when it calls a method with a time-out parameter. A thread lies in this state until the timeout is completed or until a notification is received.
Explain the Terminated state Thread.
A thread terminates because 1 of 2 things:
the entired code has been executed normally OR
because there occurred some event, like segmentation fault or unhandled exception.
What is a functional interface in Java?
An interface that contains exactly one abstract method. It can have any number of default, static methods but only one abstract method.
4 reasons to use a Lambda expression?
- REduced lines of code
- sequential and parallel execution support
- passing behaviors into methods
higher efficiency with laziness.
What is a lambda expression?
A short block of code which takes in parameters and retursn a value. They are similar to methods but they do not need a name and they can be implemented right in the body of a method.
What is needed to store a lambda expression in a variable?
Consumer intreface in the java.util.function package.
import java.util.function.Consumer;
What does the forEach loop do?
it performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Write the following code:
class Main
ArrayList Integer called Numbers
add 23,32,45,63.
use a forEach loop to print the numbers.

Describe the Thread model.

What is Gradle? Explain.
Gradle is a build automation tool. A build auto tool use used to automate the creation of applications. This include compiling, linkning, and packaging the code.
What is a join() method java?
What is the type?
What is the exception?
Allows one thread to wait until another thread completes its execution. Simply, it waits for the other thread to die.
- void type.
- InterruptedException
Explain isAlive() method.
method of thread claass tests if the thread is alive. This method returns true if the Thread is still running and not finished.
Explain the Producer/Consumer problem. What is happening in a producer/consumer problem?
This is a multi-process synchronization problem.
The producer and consumer share a common, fixed-size buffer used as a queue. The producer’s job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming data (removing from the buffer), one piece at a time.
How do we solve a producer/consumer problem? Explain.
- We make sure that the producer won’t try to add data into the buffer if its’ full AND that the consumer won’t try to remove data from an empty buffer.
- The producer is to either go to sleep or discard data if the buffer is full.
- If the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again
What keywords are used for Exception handling?
Try, Catch, Finally, Throw, Throws
Explain the Try keyword
Used to specify the block of code that might give rise to the exception in a special block with a “Try” keyword.
Explain the Catch block keyword.
catch block follows the try block that raises an exception. The keyword catch should always be used with a try.
Explain the Finally keyword
Sometimes we have an important code in our program that needs to be executed irrespective of whether or not the exception is thrown. This code is placed in a special block starting with the “Finally” keyword. The Finally block follows the Try-catch block.
Explain the Throw keyword.
With this keyword you can throw an exception if we are checking a part of the code.
Explain the Throws keyword.
The Throws keyword is used to declare exceptions. This is used to indicate that an exception might occur in the program or method.
What is the finalize() method?
a method of Object class which the Garabge Collector always calls just before the deletion/destroying of the object which is eligible.
What is a marker interface? Give 3 examples of Markter interfaces used in real-time applications.
An empty interface.
- Cloneable interface
- Serializable Interface
- Remote interface.
What is a cloneable interface? which package is it in?
A cloneable interface is in the java.lang package. It is an interface that invokes the method clone(). A class that implements the clonebale interface indicates that it is legal for clone() method to make a field-for-field copy of instances of that class.
What is a serializable interface? which package is it in?
java.io package.
It is used to make an object eligible for saving its state into a file.
What is a remote interface? which package is it in?
java.rmi
A remote object is an object which is stored at one machine and accessed from another machine. You make an object a remote object by using a Remote interface.
Explain Generalization and Specialization.
Generalization is the process of extracting shared characterisitics from two or more lasses and combingin them into a generalized superclass.
Specialization means creating new subclasses from an existing class.
What are FileWriter and FileReader used for?
They are classes that are used to write and read data from text files.
Explain FileWriter
A file handling class that is meant for writing streams of characters.
Explain Each Constructor:
FileWriter(File file)
FileWriter (File file, boolean append)
FileWriter (FileDescriptor fd)
FileWriter (String fileName)
FileWriter (String fileName, Boolean append)
FileWriter(File file) – Constructs a FileWriter object given a File object.
FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
FileWriter (String fileName) – constructs a FileWriter object given a file name.
FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.
What is a FileReader?
meant for reading streams of characters.
Explain the following constructors:
FileReader(File file)
FileReader(FileDescripter fd)
FileReader(String fileName)
FileReader(File file) – Creates a FileReader , given the File to read from
FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from
FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from
What is a Singleton Class.
A class that can only have one object(an instance of the class) at time.
What is a dependency injection?
a technique in which an object receives other objects that it depends on, called dependencies.
What happens in factory design pattern?
In factory design pattern we create an object from a factory class without exposing the creation logic to the client. Objects will be created by an interface or abstract class.
What is the main advantage of factory design patttern?
it provides loose-coupling.
What is loose-coupling?
When two classes,modules, or components have low dependencies on each other.
What is loggin gin java?
an API that provides the ability to trace out the errors of the applications.
What are the components of logging in java?
Loggers.
Logging Handlers or Appender
Logging Formatters or Layouts.
What are Loggers?
The code used by the client sends the log request to the Logger objects.
These logger objects keep track of a log level that is insterted in.
So, it is responsible for capturing log records. After that, it passes the records to the corresponding appender.
Describe the following Log Handlers…
StreamHandler:
ConsoleHandler:
FileHandler:
MemoryHandler:
SocketHandler:
StreamHandler: It writes the formatted log message to an OutputStream.
ConsoleHandler: It writes all the formatted log messages to the console.
FileHandler: It writes the log message either to a single file or a group of rotating log files in the XML format.
SocketHandler: It writes the log message to the remote TCP ports.
MemoryHandler: It handles the buffer log records resides in the memory.
What are collections in Java?
A general data structure that contains Objects. Also the name of the API
What are the interfaces in the Collections API?
Iterable, Collection, List, Queue, Set, Map, SortedSet, SortedMap
What is the difference between a Set and a List?
Set does not allow duplicates (its members are unique)
What is the difference between a Array and an ArrayList?
An array is static and its size cannot be changed, but an ArrayList can grow/shrink
What is the difference between ArrayList and Vector?
Vector is synchronized whereas ArrayList is not.
What is the difference between TreeSet and HashSet?
The two general purpose Set implementations are HashSet and TreeSet. HashSet is much faster (constant time versus log time for most operations) but offers no ordering guarantees.
What is the difference between HashTable and HashMap?
a. Hashtable is synchronized whereas Hashmap is not.
b. Hashmap permits null values and the null key.
Are Maps in the Collections API?
Yes, but they do not implement Collection or Iterable interfaces
What are generics? What is the diamond operator (<>)?
A way of specifying a type within a data structure - they enforce type safety. <> operator lets you infer generic types from the LHS of assignment operation
What is multi-threading?
Handling multiple threads / paths of execution in your program.
In what ways can you create a thread?
By extending the Thread Class or by implementing the Runnable Interface. You must call Thread’s .start() method to start it as a new thread of execution.
Lifecycle of a thread
When created, in NEW state.
When .start() is called, it goes to RUNNABLE state.
When .run() is called, goes to RUNNING state.
If .sleep() or .wait() is called, will go to WAITING.
If dependent on another thread to release a lock, it will go to BLOCKED state.
When finished executing, will be in DEAD state and cannot be restarted.
What is deadlock?
When two or more threads are waiting on locks held by the others, such that no thread can execute
What is synchronized keyword?
Only allowing one thread access to the method or variable at a time - enforces thread-safety
What is a Marker interface?
A marker interface is an interface which has no methods at all. Example: Serializable, Remote, Cloneable. Generally, they are used to give additional information about the behavior of a class.
What are transient variables?
Transient variables are those variables which cannot be serialized.
Difference between FileReader and BufferedReader?
FileReader is just a Reader which reads a file, so it reads characters and uses the platform-default encoding.
BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines (e.g. can read one line at a time).
So you can wrap a BufferedReader around a FileReader
What are Singleton / Factory design patterns?
Singleton - allows for creation of only 1 object. Method for retrieving object returns reference to the same object in memory. Implement via private constructor
Factory - abstracts away instantiation logic, usually used in conjunction with singleton pattern
What is an advantage to using a logging library?
Allows you to set logging thresholds
What is log4j?
Logging library for Java
What are the logging levels of log4j?
TRACE, DEBUG, INFO, WARN, ERROR, FATAL
What are functional interfaces?
Functional interfaces only have one method, and can be used in conjuntion with lambdas
What are lambdas?
Like anonymous functions, they allow implementation of functional interfaces directly without creating a class
What is try-with-resources? What interface must the resource implement to use this feature?
Try-with-resources allows for automatically closing resources in a try/catch block using try(resource) {…} syntax. Must implement the AutoCloseable interface
How to make numbers in your code more readable?
Use the _ for numeric literals - must be placed between numbers
Which collections cannot hold null values?
HashTable, TreeSet, ArrayDeque, PriorityQueue
If 2 interfaces have default methods and you implement both, what happens?
The code will NOT compile unless you override the method. However, the code WILL compile if one interface is implemented further up in the class hierarchy than the other - in this case, the closest method implementation in the hierarchy will be called
If 2 interfaces have same variable names and you implement both, what happens?
The code will compile unless you make a reference to the variable (this is an ambiguous reference). You must explicitly define the variable by using the interface name: int a = INTERFACENAME.a;
Why does HashTable not take null key?
The hash table hashes the keys given as input, and the null value cannot be hashed
What new syntax for creating variables was introduced with Java 10?
The var keyword was introduced - with type inference
Is there an interactive REPL tool for Java like there is for languages like Python?
Yes, the jshell tool introduced in Java 9
What are collection factory methods?
They allow you to directly populate collections, e.g. Set.of(1,2,3)
What is wrong with this line of code? Set myints = new HashSet<>()
Primitives cannot be used with collections; instead, use the wrapper class
If you want to set up custom ordering of objects in a collection, use the Comparator interface. T/F
True
Which logging threshold level is default if not explicitly configured?
DEBUG
Which collection should I use if I want it to store sorted, unique values?
TreeSet
If I add 3 of the same exact object to a HashSet, how many will be stored?
1
What is the purpose of multithreading?
Improve application performance and concurrency when done correctly.
If a thread’s state becomes “not running” because its wait() method is invoked, which method needs to be invoked to test all waiting threads to see if they should wake up again?
notifyAll();
Which of the following is true about log4j levels?
A log request of level x in a logger with level y is enabled if x >= y.
A log request assumes that levels are ordered.
For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
All of the above.
All of the above.
ERROR is a higher logging level than FATAL. t/f?
True
INFO is a higher logging level than DEBUG.
False
Which of the following statements are correct concerning log4j?
log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License.
log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.
log4j is highly configurable through external configuration files at runtime.
All of the above.
All of the above.
Which is true about an Iterator?
It enables the traversal through a collection.
HashMaps can contain null values and a null key. t/f?
True
What is the difference between ArrayDeque and PriorityQueue?
ArrayDeque is an implementation of a pure double-ended queue (elements can be added or removed from either end of the queue). PriorityQueue is an implementation of a queue that does not have specified ends (addition or removal of elements doesn’t happen on any specific end of the queue).
True or false: Logging is the process of writing log messages during the execution of a program to a central place and allows you to report and persist error and warning messages as well as info messages so that the messages can later be retrieved and analyzed.
True
True or false: The Map interface is a part of the Java Collection interface.
False
Define Queue
A collection interface that holds and processes elements in FIFO order.
Putting @FunctionalInterface above an Interface declaration designates to the compiler that it is a Functional Interface. t/f
True
CheckedException and RuntimeException are two classes that inherit from the Exception class. t/f
False
Even in the waiting state a thread is still running
False
Is it possible to start a thread multiple times?
False
A static method can be synchronized
True
What is synchronization?
The capability to control the access of multiple threads to shared resources.
What is this piece of code doing?
(byte i) -> 10+i;
Passes a byte argument i, and returns 10+i
(double x, y) -> x - y; is this a valid lambda expression? t/f
False.
Functional interfaces have a single functionality to exhibit. t/f?
True
What is a Set in jAva?
The set is an interface from the Collection hierarchyl.
What are some methods that we can use on a Set in Java? (Choose all options that are correct)
.add()
.length()
.contains()
.remove()
.add()
.contains()
.remove()
A set can contain duplicate values. t/f?
False.
A set is sorted t/f
False
What are some methods that we can use on a List in Java? (Choose all options that are correct)
.add()
.size()
.isEmpty()
.length()
.add()
.size()
.isEmpty()
Which PriorityQueue method specifically returns the item at the head but does not remove it from the queue?
peek()
Why would you want to use a PriorityQueue?
To store potentially duplicate objects by insertion order.
What are some advantages and disadvantages of using multithreading in an application?
Advantages: improve performance & efficiency for parallel processing
Disadvantages: deadlocking threads, race conditions, hard to debug & maintain
What are Lamda expressions primary use?
to define inline implementation of a functional interface.
Lambda expressions fulfills the need for anonymous classes in java? t/f
True
What is a thread?
A representation of a path of execution, allowing for concurrent processing
Which Thread method is used to wait for the thread to finish execution?
Thread.join()
Threads can be created by extending the Runnable class. t/f
false
Threads can be created by…
passing a Runnable into the constructor of Thread: new Thread(Runnable)
The run() method comes from the Thread class. t/f
False
What happens when thread’s sleep() method is called?
Thread returns to the waiting state.
What is currentThread()?
It is a Thread public static method used to obtain a reference to the current thread.
Which method must be implemented by all threads?
run()
Explain the final keyword.
The final keyword is a non-access modifier which can be used for class, method, and variables.
Explain a final variable
final variable’s value can’t be modified. You must initialize a final variable.
Three ways to initialize a final variable.
- You can initialize a final variable when it is declared. if not initialized when declared, it is called a blank final variable.
- a blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them.
- A blank final static variable can be initialized inside a static block.