Week 3 + Week 2 and 1 Review Flashcards

(252 cards)

1
Q

What is a generic type?

A

A generic class or interface that is parameterized over types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why use Generics?

A

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Two types of generics? What does each do?

A

Generic method - introduce their own type parameters.
Generic class -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a generic method?

A

Exactly like a normal method but a generic method has type parameters that are cited by actual type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Benefits of generic code over non-generic?

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are generics commonly used with?

A

Collections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a generic called when declared on a class?

A

Generic type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why are generics useful?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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());

A

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());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the Collections Framework?

A

A set of classes and interfaces that implement commonly used data structures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a collection?

A

A single object which acts as a container for other objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Are collections iterable?

A

yes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Main difference between Collection and Map?

A

Collection’s are iterable, maps are not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Three interfaces derived from the Collection interface?

A

List.
Queue.
Set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Classes derived from the List interface?

A

ArrayList.
Vector.
LinkedList.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Classes derived from the Queue interface?

A

LinkedList.
Priority Queue.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Classes derived from the Set interface?

A

Hash Set.
Linked Hash Set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a List in Java?

A

A collection that is ordered and preserves the ordered in which elements are inserted into the list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a Vector?

A

An older class which implements List.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

A thread safe implementation of an ArrayList.

A

Vector.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What should you use for implementing a stack?

A

ArrayDeque.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

ArrayList(class) implements _______ which extends _______.

A

List (interface)
Collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Set Extends _______ which Extends ________ which Implements ________.

A

Sorted Set.
Navigable Set.
Treeset.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the Set interface?

A

an unordered collection of objects in which duplicate values cannot be stored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How can I make the following code generic? public class Printer { }
Add the type parameter after the class name. public class Printer { }
26
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();
27
Generics work with primitive types and wrapper class objects.
False. Generics don't work with primitive types.
28
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") ).
29
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.
30
Which package is List found in?
java.util
31
Which interface does List inherit?
Collection
32
What are the four implementation classes of List interface?
ArrayList. LinkedList. Stack. Vector.
33
Declare an array of the names of 4 friends. Call it friendsArray.
String[] friendsArray = new String[4];
34
Declare an array of your friends with the names... John, Steph, Sam, Amy. Call it friendsArray
String[] friendsArray = {"John", "Steph", "Sam", "Amy"};
35
Declare an ArrayList with reference name friendsArrayList.
ArrayList friendsArrayList = new ArrayList\<\>();
36
What is the import for ArrayList?
java.util.ArrayList
37
Which have a fixed size, Array or ArrayList? or neither? or Both?
Array's have a fixed size.
38
Declare an ArrayList called friendsArrayList that holds the values John, Chris, Eric, and Luke.
ArrayList friendsArrayList = new ArrayList\<\>(Arrays.asList("John", "Chris", "Eric", "Luke" ));
39
How can you print out "Steph" from the Array? String[] friendsArray = {"John", "Steph", "Sam", "Amy"};
System.out.println(friendsArray[1]);
40
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));
41
How would I get the length of an Array called friendsArray? Show code.
System.out.println(friendsArray.length);
42
How would I get the length of an ArrayList called friendsArrayList? Show code.
System.out.println(friendsArrayList.size());
43
how would I add string "Mitch" to an ArrayList called friendsArrayList?
friendsArrayList.add("Mitch");
44
How would I change the first value in an Array called friendsArray to "Carl"?
friendsArray[0] = "Carl";
45
How would I change the first value in an ArrayList called friendsArrayList to "Carl"?
friendsArrayList.set(0, "Carl");
46
How would I remove "Chris" from an ArrayList called friendsArrayList?
friendsArrayList.remove("Chris");
47
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();
48
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)
49
Which package are Maps in ?
java.util package
50
What is a map?
An interface that represents a mapping between a key and a value.
51
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.
52
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.
53
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.
54
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.
55
A constructor requires a return type? T/F?
False. a constructur can NOT have a return type.
56
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.
57
What would I use if i wanted to iterate over a data structure?
for loop
58
count from 1-5 using a for loop.
for (int i = 0; i \<= 5; i++) System.out.println(i);
59
count from 1-5 using a while loop.
i = 1; while (i \<=5) { System.out.println(i); i++;
60
import a Scanner.
import java.util.Scanner
61
create a Scanner object called scan.
Scanner scan = new Scanner(System.in);
62
What is java type casting? Two types.
When you assign a value of one primitive data type to another type. Wide (automatically) narrow (manually)
63
When do I need to use casting?
When passing a smaller size type into a larger type size.
64
Cast the following code: go from double to int. name int variable 'y' double x = 9.5;
int y = (int) x;
65
Write code that manually boxes the following code. Name variable y. double x = 5;
double y = new Double(x);
66
What are the two types of constructors?
No args. Parameterized.
67
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; } } ```
68
Add a paramterized constructor to the following code: ``` class myClass { int x = 5; ```
myClass(int i) { x = i
69
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.
70
If i use the private access modifier, what will use to retrieve and change information within a private modifier.
Getters and Setters.
71
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.
72
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.
73
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.
74
What is an abstract class?
A class that you can NOT instantiate.
75
How do you create an abstract class? show code in example of public class called Animal.
public abstract class Animal { }
76
What is an abstract method?
A method within an abstract class.
77
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.
78
Name all non-access modifiers.
static. final. abstract. synchornized. transient. volatile. strictfp.
79
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.
80
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.
81
What is TDD?
test driven development. This is when you use tests to drive the development of the application.
82
3 steps to Workflow of TDD?
1. Start by writing a unit test related to the feature you want to implement. 2. Make the test pass by writing the lease possible amount of code. 3. Refactor in order to get rid of duplication or other problems (optional).
83
What does JUnit Annotations @Test do?
declares a method as a test method.
84
What does JUnit Anootation @BeforeClass do?
declares a setup method that runs once, before all other methods in the class.
85
What does JUnit Annotation @Before do?
decalres a setup method that runs before each test method.
86
What does JUnit annotations @After do?
declares a tear-down method that runs before each test method.
87
What does JUnit Annotations @AfterClass do?
Declares a tear-dpwn method that runs once, after all other methods in the class.
88
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.
89
What is an exception in java?
an unwanted or unexpected event.
90
When an exceptions occurrs within a method, it creates an \_\_\_\_\_\_. This is called an \_\_\_\_\_\_\_\_.
object. exception object.
91
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.
92
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.
93
What is a try/catch block used for?
to handle exceptions that could be thrown in our application.
94
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.
95
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.
96
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")
97
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);
98
which package is LinkedList in?
java.util
99
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); } }
100
What is an ArrayDeque?
A special kind of growable array that allows us to add or remove an element from both sides.
101
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.
102
Write a line of code that would retrieve the first element from an Array Deque called animals. Call it firstElement.
String firstElement = animals.getFirst()
103
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.
104
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
105
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 print
106
Declare a two dimensional array of ints
int [] []
107
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]
108
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).
109
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.
110
which package is comparable interface found in?
java.lang
111
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.
112
What is garbage collection in java?
process by which java programs perform automatic memory management.
113
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.
114
What does the constructor, StringBuilder(), do?
It creates an empty String Builder with intial capacity of 16.
115
What does the constructor, StringBuilder(String str), do?
It creates a String Builder with a specified string.
116
What does the constructor, StringBuilder(int length), do?
It creates an empty String Builder with the specified capacity as length.
117
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.
118
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.
119
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.
120
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.
121
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.
122
import Thread class package.
import java.lang.Thread;
123
Two ways to create a Thread.
extending the Thread class and overriding the run() method. OR implement Runnable interface.
124
created a Thread through extension using the following: class Main print out "This is a thread" use a run() method.
125
What are the 6 thread states?
New. Runnable. Blocked. Waiting. Time Waiting. Terminated.
126
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.
127
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.
128
Explain blocked/waiting Thread state.
When a thread is temporarily inactive it is either blocked or waiting.
129
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.
130
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.
131
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.
132
4 reasons to use a Lambda expression?
- REduced lines of code - sequential and parallel execution support - passing behaviors into methods higher efficiency with laziness.
133
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.
134
What is needed to store a lambda expression in a variable?
Consumer intreface in the java.util.function package. import java.util.function.Consumer;
135
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.
136
Write the following code: class Main ArrayList Integer called Numbers add 23,32,45,63. use a forEach loop to print the numbers.
137
Describe the Thread model.
138
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.
139
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
140
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.
141
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.
142
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
143
144
What keywords are used for Exception handling?
Try, Catch, Finally, Throw, Throws
145
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.
146
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.
147
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.
148
Explain the Throw keyword.
With this keyword you can throw an exception if we are checking a part of the code.
149
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.
150
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.
151
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.
152
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.
153
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.
154
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.
155
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.
156
What are FileWriter and FileReader used for?
They are classes that are used to write and read data from text files.
157
Explain FileWriter
A file handling class that is meant for writing streams of characters.
158
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.
159
160
What is a FileReader?
meant for reading streams of characters.
161
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
162
What is a Singleton Class.
A class that can only have one object(an instance of the class) at time.
163
What is a dependency injection?
a technique in which an object receives other objects that it depends on, called dependencies.
164
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.
165
What is the main advantage of factory design patttern?
it provides loose-coupling.
166
What is loose-coupling?
When two classes,modules, or components have low dependencies on each other.
167
168
What is loggin gin java?
an API that provides the ability to trace out the errors of the applications.
169
What are the components of logging in java?
Loggers. Logging Handlers or Appender Logging Formatters or Layouts.
170
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.
171
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.
172
What are collections in Java?
A general data structure that contains Objects. Also the name of the API
173
What are the interfaces in the Collections API?
Iterable, Collection, List, Queue, Set, Map, SortedSet, SortedMap
174
What is the difference between a Set and a List?
Set does not allow duplicates (its members are unique)
175
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
176
What is the difference between ArrayList and Vector?
Vector is synchronized whereas ArrayList is not.
177
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.
178
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.
179
Are Maps in the Collections API?
Yes, but they do not implement Collection or Iterable interfaces
180
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
181
What is multi-threading?
Handling multiple threads / paths of execution in your program.
182
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.
183
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.
184
What is deadlock?
When two or more threads are waiting on locks held by the others, such that no thread can execute
185
What is synchronized keyword?
Only allowing one thread access to the method or variable at a time - enforces thread-safety
186
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.
187
What are transient variables?
Transient variables are those variables which cannot be serialized.
188
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
189
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
190
What is an advantage to using a logging library?
Allows you to set logging thresholds
191
What is log4j?
Logging library for Java
192
What are the logging levels of log4j?
TRACE, DEBUG, INFO, WARN, ERROR, FATAL
193
What are functional interfaces?
Functional interfaces only have one method, and can be used in conjuntion with lambdas
194
What are lambdas?
Like anonymous functions, they allow implementation of functional interfaces directly without creating a class
195
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
196
How to make numbers in your code more readable?
Use the _ for numeric literals - must be placed between numbers
197
Which collections cannot hold null values?
HashTable, TreeSet, ArrayDeque, PriorityQueue
198
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
199
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;
200
Why does HashTable not take null key?
The hash table hashes the keys given as input, and the null value cannot be hashed
201
What new syntax for creating variables was introduced with Java 10?
The var keyword was introduced - with type inference
202
Is there an interactive REPL tool for Java like there is for languages like Python?
Yes, the jshell tool introduced in Java 9
203
What are collection factory methods?
They allow you to directly populate collections, e.g. Set.of(1,2,3)
204
What is wrong with this line of code? Set myints = new HashSet\<\>()
Primitives cannot be used with collections; instead, use the wrapper class
205
If you want to set up custom ordering of objects in a collection, use the Comparator interface. T/F
True
206
Which logging threshold level is default if not explicitly configured?
DEBUG
207
Which collection should I use if I want it to store sorted, unique values?
TreeSet
208
If I add 3 of the same exact object to a HashSet, how many will be stored?
1
209
What is the purpose of multithreading?
Improve application performance and concurrency when done correctly.
210
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();
211
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.
212
ERROR is a higher logging level than FATAL. t/f?
True
213
INFO is a higher logging level than DEBUG.
False
214
Which of the following statements are correct concerning log4j? ## Footnote 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.
215
Which is true about an Iterator?
It enables the traversal through a collection.
216
HashMaps can contain null values and a null key. t/f?
True
217
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).
218
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
219
True or false: The Map interface is a part of the Java Collection interface.
False
220
221
Define Queue
A collection interface that holds and processes elements in FIFO order.
222
Putting @FunctionalInterface above an Interface declaration designates to the compiler that it is a Functional Interface. t/f
True
223
CheckedException and RuntimeException are two classes that inherit from the Exception class. t/f
False
224
Even in the waiting state a thread is still running
False
225
Is it possible to start a thread multiple times?
False
226
A static method can be synchronized
True
227
What is synchronization?
The capability to control the access of multiple threads to shared resources.
228
What is this piece of code doing? (byte i) -\> 10+i;
Passes a byte argument i, and returns 10+i
229
(double x, y) -\> x - y; is this a valid lambda expression? t/f
False.
230
Functional interfaces have a single functionality to exhibit. t/f?
True
231
What is a Set in jAva?
The set is an interface from the Collection hierarchyl.
232
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()
233
A set can contain duplicate values. t/f?
False.
234
A set is sorted t/f
False
235
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()
236
Which PriorityQueue method specifically returns the item at the head but does not remove it from the queue?
peek()
237
Why would you want to use a PriorityQueue?
To store potentially duplicate objects by insertion order.
238
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
239
What are Lamda expressions primary use?
to define inline implementation of a functional interface.
240
Lambda expressions fulfills the need for anonymous classes in java? t/f
True
241
What is a thread?
A representation of a path of execution, allowing for concurrent processing
242
Which Thread method is used to wait for the thread to finish execution?
Thread.join()
243
Threads can be created by extending the Runnable class. t/f
false
244
Threads can be created by...
passing a Runnable into the constructor of Thread: new Thread(Runnable)
245
The run() method comes from the Thread class. t/f
False
246
What happens when thread's sleep() method is called?
Thread returns to the waiting state.
247
What is currentThread()?
It is a Thread public static method used to obtain a reference to the current thread.
248
Which method must be implemented by all threads?
run()
249
Explain the final keyword.
The final keyword is a non-access modifier which can be used for class, method, and variables.
250
Explain a final variable
final variable's value can't be modified. You must initialize a final variable.
251
Three ways to initialize a final variable.
1. You can initialize a final variable when it is declared. if not initialized when declared, it is called a blank final variable. 2. 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. 3. A blank final static variable can be initialized inside a static block.
252